i have a parent child situation with for example my user class and my userwork child class (Entity framework scaffolded classes). i used the controller wizard to scaffold CRUD methods and views. it scaffolded two Create method’s, the Get and the httpPost methods.
In a normal scenario i would want to be passing in the user’s id into the get so that it would be passed into the model which is being populated in html.beginform() section and then it would subsequently be passed into thepost.
I am unsure what is the correct method to do this? I have modified the Get as below
public ActionResult Create(int id)
{
this.ViewData.Add("id", id);
return View();
}
and the Create.shtml as below
@model UserWork
@{
ViewBag.Title = "Create";
int id = (int)ViewData["id"];
}
<h2>Create</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
@using (Html.BeginForm(routeValues:new {user_id = @id})) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Userwork</legend>
<div class="editor-label">
@Html.LabelFor(model => model.user_id)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.user_id)
@Html.ValidationMessageFor(model => model.user_id)
</div>
......
(i left the scaffolded user_id fields as editable so i could test seeing them prepopulated when the form loads) which the form loads it doesnt have my id value in the fields, Is this the correct method of achieving this?
Cheers
Tim
So my initial question raised several other questions about my understanding of MVC and routing. i established that if i pass one parameter as an integer to the route in the form
if my action method is in the form
everything is cool but if its in the form
then i was getting an exception that the required parameter user_id wasnt populated.
I added an additional mapping as below and this seems to be correctly populating the view.
I decided not to instantiate the model and pass it into the view as using the route above it passes the userid into the model’s user_id field correctly.
Cheers
Tim