我试图让用户创建一个对象并将其保存到数据库中。我已经正确地搭建了所有脚手架等,并将我的控件修改为以下内容:
Function Create(id As Integer) As ViewResult
ViewBag.id = id
Dim job As Job = New Job
job.CustomerId = id
job.JobAmount = 0
job.JobDate = Date.Now()
job.JobStatus = "Active"
Return View(job)
End Function
然后返回以下视图:
@ModelType Laundry.Job
@Code
ViewData("Title") = "Create"
End Code
<h2>Create</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@Using Html.BeginForm()
@Html.ValidationSummary(True)
@<fieldset>
<legend>Job</legend>
<div class="editor-label">
@Html.LabelFor(Function(model) model.JobDate)
</div>
<div class="editor-field">
@Html.EditorFor(Function(model) model.JobDate)
@Html.ValidationMessageFor(Function(model) model.JobDate)
</div>
<div class="editor-label">
@Html.LabelFor(Function(model) model.BillId)
</div>
<div class="editor-field">
@Html.EditorFor(Function(model) model.BillId)
@Html.ValidationMessageFor(Function(model) model.BillId)
</div>
<div class="editor-label">
@Html.LabelFor(Function(model) model.CustomerId)
</div>
<div class="editor-field">
@Html.EditorFor(Function(model) model.CustomerId)
@Html.ValidationMessageFor(Function(model) model.CustomerId)
</div>
<div class="editor-label">
@Html.LabelFor(Function(model) model.JobStatus)
</div>
<div class="editor-field">
@Html.EditorFor(Function(model) model.JobStatus)
@Html.ValidationMessageFor(Function(model) model.JobStatus)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
End Using
<div>
@Html.ActionLink("Back to List", "Index")
</div>
我创建了一个作业实例并将其通过控制器传递给视图,以便默认某些值。具体来说,我需要创建一个带有传递给控制器的 id 的作业对象,但我不希望用户能够编辑这个 id(他们不应该看到这个)。我想如果我只是从我的观点中删除以下内容:
<div class="editor-label">
@Html.LabelFor(Function(model) model.CustomerId)
</div>
<div class="editor-field">
@Html.EditorFor(Function(model) model.CustomerId)
@Html.ValidationMessageFor(Function(model) model.CustomerId)
</div>
该对象仍会使用我在控制器中设置的 customerId 保存,但是如果我在保存时删除此代码,它将 customerid 保存为 0,并且当它在那里正常工作但用户可以查看和编辑它时,它似乎会保存。
我这样做正确吗?