I am trying to let a user create an object and save it to the database. I have scaffolded it all correctly etc and have modified my control to the following:
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
This then returns the following view:
@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>
I created a instance of job and passed it through the controller to the view in order to default certain values. Specifically I need to create a job object with the id passed to the controller but I do not want the user to be able to edit this id (they should not see this). I thought that if I simply deleted the following from my view:
<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>
The object would still save with the customerId I set in my controller however it seems if I delete this code when it saves it saves the customerid as 0 and when its there it works correctly but the user can see and edit it.
Am I doing this correctly?
Use
@Html.HiddenFor(Function(model) model.CustomerId)for this. It will persist the value from view to controller, but not be visible to the user.