Reputation: 320
is it possible to send an object from a strongly typed view to the Controller via Http-POST that does not equal the type of the original model.
For example:
I have a ViewModel like this:
public class PersonsViewModel
{
List<PersonViewModel> persons { get; set; }
PersonsViewModel() { }
}
public class PersonViewModel
{
//some properties
Person() { }
}
Now i have this View:
@model PersonsViewModel
<div>
@for(int i = 0; i > Model.persons.Count; i++)
{
@Html.EditorFor(Model.persons[i])
}
</div>
The editor could look like this:
@model PersonViewModel
<div>
@using (Html.Beginform("Postaction","Controller", FormMethod.Post)){
<div>
<!-- properties and textboxes here + submit button -->
</div>
}
<div>
The controller action
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult Postaction(PersonViewModel model)
{
//do something
}
}
This doesn't work because it seems the Controller is expecting a PersonsViewModel object. My workaround so far is to make a "big" Form that contains all PersonViewModel and send the complete PersonsViewModel to the controller.
Is it somehow possible to pass only one PersonViewModel to the Controller although the view is strongly typed?
Kind regards, Martin
Upvotes: 4
Views: 7295
Reputation: 8781
It could be done:
When used with collections Html.EditorFor
is smart enough to generate input names that contain index so ModelBinder
could successfully create a model as a collection of objects. In your case since you want to have a separate form per PersonViewModel
object, you could create a partial view as a template for editing PersonViewModel
and use Html.RenderPartial
helper:
Assuming you have _PersonViewModel.cshtml
partial view
@for(int i = 0; i > Model.persons.Count; i++)
{
Html.RenderPartial("_PersonViewModel", Model.persons[i]);
}
in the _PersonViewModel.cshtml you can not use neither one of editor helpers such as Html.EditorFor
, Html.TextboxFor
because they are going to generate identical ids for the same properties so you will have to manually create html inputs:
@model PersonViewModel
<div>
@using (Html.Beginform("Postaction","Controller", FormMethod.Post)){
<div>
@*Nottice the usage of Html.NameFor(m=>m.FirstName) for generating a name property value *@
<input type="text" name="@Html.NameFor(m=>m.FirstName)" value="@Model.FirstName">
</div>
}
<div>
This way you can post a single PersonViewModel
object to the controller action
Upvotes: 6