Reputation: 38519
I've got an action on my controller that looks like this:
[HttpPost]
public ActionResult Edit(EditMyObjectViewModel editMyObjectViewModel)
{
}
EditMyActionViewModel
contains a MyObject
This is passed in to the Edit view (the GET version of the above controller action)
When it is posted back in, the ID isn't set....
If I change the controller to be:
[HttpPost]
public ActionResult Edit(Guid id, EditMyObjectViewModel editMyObjectViewModel)
{
editMyObjectViewModel.ID = id;
}
That works, but it seems a little wrong?
I guess I could also bind a hidden field on the view to Model.ID?
What's the convention here?
EDIT
Model / ViewModels are as follows:
public class EditMyObjectViewModel
{
public IEnumerable<SomeItem> SomeUnrelatedStuff { get; set; }
public MyObject MyObject { get; set; }
}
public class MyObject
{
public guid ID { get; set; }
public string Name { get; set; }
}
View is as follows:
@model MyApp.Models.EditMyObjectViewModel
@using (Html.BeginForm("Edit", "License", FormMethod.Post, new { @class = "form form-horizontal" }))
{
@Html.TextboxFor(x=>x.MyObject.Name);
<input type="submit" class="btn btn-success" value="Create Modification" />
}
Upvotes: 3
Views: 3354
Reputation: 7484
You are right, you either need to create a hidden field to hold the id or you need to add the ID as a parameter to the action method.
The issue is simply where the id comes from and how it gets populated. The default model binder populates the model from form fields; it wont' use a query parameter. And the query parameter won't go into the model but it will get populated in an argument on the action method.
The one other thing you could do is to create a custom model binder to populate the query parameter into the model. But that feels like overkill in this situation. Plus, you'd have to do this for each page/model.
It it was me, I'd add the id to the action method.
Upvotes: 8