开发者

Using multiple partial views in MVC3 razor forms

I have an insurance entry form that has contact information for two people. I have created a Razor partial view for the contact entry and put it in the form twice. The 'master' view model (VmApplicationForm) contains two instances of a subsidiary view model (VmPolicyHolder) corresponding to the two contacts as well as some properties common to both contacts. I am calling @Html.RenderPartial("_CreateOrEdit", Model.contactInfo1) and @Html.RenderPartial("_CreateOrEdit", Model.contactInfo2) in the page. With this arrangement (no surprises) the rendered code has duplicate IDs for the form input elements.

Is 开发者_开发问答there any way of getting RenderPartial to prefix the IDs and Name attributes? I couldn't see this in the documentation, but perhaps I've missed something.


Sorry, I don't have time yet to give you the example code, but i'll give you the idea. You should first create EditorTemplate for that probably called ContactInfo class. And then, in the base class(Holding that two contacts) edit view, you should write

@Html.EditorFor(model => model.contactInfo1)
@Html.EditorFor(model => model.contactInfo2)

This way, it will render that EditorTemplate and generate correct ids and names to inputs within it.


What you are doing is trying to post a collection of items in a form- this can indeed be done in MVC (as well as in any web page/application that uses a FORM tag), however it requires some special handling to avoid id collisions and to correctly format the post data. Steve Sanderson has a great post on how to accomplish this:

http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/

Essentially its a wrapper to append unique guids to element ids (in your case for each contactInfo), and create the proper array format in the tags. eg <input name="ContactInfo[f2cc4d6b-fc32-45e9-9d3d-fce54c3fede3].FirstName">

if your model is something like ContactInfo, you will end up posting like

[HttpPost]
public ActionResult Index(IEnumerable<ContactInfo> contacts)
{
    // To do: do whatever you want with the data
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜