Getting id's on elements in partial views
I have a view that - among other things - contains a list of elements. I want to reuse this list, so I move it out to a partial view. My view contains a form, and on post I want to include some values in the list. Therefore I use @Html.EditorFor(m => m.Something)
to generate input-boxes which will get a unique Id. The view is strongly typed to use "MyModel" as Model. On post the MVC framework handles everything very well - putting the values back together to a MyModel object containing the input and some fields I used Html.HiddenFor
on. All good.
Now I move this to a partial view. The partial view only works on the list and therefore is strongly typed to model List. I include this view from my main view, and pass in the list I want it to render. The table code inside the partial view is exactly what it was before except that it is changed to get values from the list instead of MyModel. All data is displayed perfectly, but there is a problem. The input-boxes doesn't get an Id any more. And because they don't get an Id their value isn't included in the posted form - and hence they don't appear in the model I get as input to my post method. I tried including the partial view using both @Html.Partial("_MyPartial", Model.Items)
and @{Html.RenderPartial("_MyPartial", Model.Items);}
So the question is; how can I make this work with a partial view? How can I get that Id back?
Here is some sample code in case anything is unclear:
MyModel.cs
----------
public class MyClass
{
public string Val1 { get; set; }
public string Val2 { get; set; }
}
public class MyModel
{
public List<MyClass> Items {get; set; }
}
MyView.cshtml:
--------------
@model MyModel
using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Post))
{
@Html.Partial("_MyP开发者_开发问答artial", Model.Items)
}
_MyPartial.cshtml:
------------------
@model List<MyClass>
<table>
<tbody>
for (var i = 0; i< Model.Count; i++)
{
<tr>
<td>
@Model[i].Val1
@Html.HiddenFor(model => model[i].Val1)
</td>
<td>@Html.EditorFor(model => model[i].Val2)</td>
</tr>
}
</tbody>
</table>
You will have to use EditorFor for your Model.Items
as well.
So change the _MyPartial to something more relevant, like MyEditorForMyClass.cshtml
.
Make a 'EditorTemplates
' folder in the Shared or the folder you're working in and place the 'MyEditorForMyClass.cshtml
' file in there.
Then do the following:
MyView.cshtml:
--------------
@model MyModel
using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Post)
{
@Html.EditorFor(model => Model.items,"MyEditorForMyClass"}
}
The EditorFor templates/helper methods allows you to render both standard data-types and your own complex objects that contain multiple properties.
精彩评论