我有一份保险登记表,其中包含两个人的联系信息。我为联系人条目创建了 Razor 部分视图,并将其放入表单中两次。 “主”视图模型 (VmApplicationForm) 包含与两个联系人相对应的辅助视图模型 (VmPolicyHolder) 的两个实例以及两个联系人共有的一些属性。我在页面中调用 @Html.RenderPartial("_CreateOrEdit", Model.contactInfo1)
和 @Html.RenderPartial("_CreateOrEdit", Model.contactInfo2)
。通过这种安排(毫不奇怪),呈现的代码对于表单输入元素具有重复的 ID。
有什么方法可以让 RenderPartial 为 ID 和 Name 属性添加前缀吗?我在文档中看不到这一点,但也许我错过了一些东西。
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.
发布评论
评论(2)
抱歉,我还没有时间给您示例代码,但我会给您这个想法。您应该首先创建 EditorTemplate
ContactInfo
类。然后,在基类(持有两个联系人)编辑视图中,您应该这样编写,它将呈现该 EditorTemplate 并为其中的输入生成正确的 id 和名称。
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 writeThis way, it will render that EditorTemplate and generate correct ids and names to inputs within it.
您正在做的是尝试以表单形式发布项目集合 - 这确实可以在 MVC 中完成(以及在使用 FORM 标记的任何网页/应用程序中),但是它需要一些特殊处理以避免 id 冲突并正确格式化发布数据。 Steve Sanderson 有一篇关于如何实现这一目标的精彩文章:
http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
本质上它是一个要附加的包装器元素 id 的唯一 guid(在您的情况下为每个 contactInfo),并在标签中创建正确的数组格式。例如
如果您的模型类似于 ContactInfo,您最终会发布类似
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