如何在 ASP.NET MVC 的同一页面中使用同一 .ascx 的两个实例?
我在 ASP.NET MVC 页面中有两个 Address.ascx
控件实例。
<h1>Shipping Address</h1>
<% Html.RenderPartial("Controls/AddressControl"); %>
<h1>Billing Address</h1>
<% Html.RenderPartial("Controls/AddressControl"); %>
当然,使用与此完全相同的代码,我最终会为地址中的每个字段提供相同的 ID。 我可以轻松地将一个字符串附加到字段的 ID 中,这样我就有了 'Street1_billing'
和 'Street1_shipping'
,但我不清楚如何将其映射到该模型。
将模型映射到项目数组的最佳解决方案是什么(在本例中只有 2 个)。 我不知道有任何 ASP.NET 对此问题有“开箱即用”的解决方案。
注意:这与这个问题略有相似,我可以使用这个解决方案来自 Scott Hanselman,但它并不完全是我想要的。 就我而言,我知道我有两个项目,所以它本质上是一个 2 项目数组,但我想知道是否有一个稍微更优雅的解决方案。
PS。 我确信这个问题之前已经被问过很多次了,但我似乎无法输入正确的搜索词。 如果您知道有骗局,请链接此问题!
I have two instances of an Address.ascx
control in an ASP.NET MVC page.
<h1>Shipping Address</h1>
<% Html.RenderPartial("Controls/AddressControl"); %>
<h1>Billing Address</h1>
<% Html.RenderPartial("Controls/AddressControl"); %>
Of course, with the code exactly like this I'll end up with the same IDs for each field in the address. I can easily append a string to the ID of the fields so I'd have 'Street1_billing'
and 'Street1_shipping'
, but I'm not clear how to map this to the model.
Whats the best solution to mapping a model to an array of items (in this case only 2).
I'm not aware of any ASP.NET 'out of the box' solution for this.
Note: This is slightly similar to this question and I could use this solution from Scott Hanselman, but its not exactly what I want. In my case I know I have two items, so its essentially a 2 item array but I'm wondering if there is a slightly more elegant solution.
PS. I'm sure this has been asked many times before, but I just cant seem to put in the right search terms. Please link this question if you're aware of dupes!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,向模型添加一个 Address 类。
在Address.ascx中,您需要在顶部有一行继承Address模型,如下所示:
在主视图控制器中,将两个地址推送到 ViewData 中。
在您的主视图中,像这样调用两个地址子视图:
First, add an Address class to the model.
In Address.ascx, you need a line at the top that inherits the Address model, like this:
In the controller for the main view, push your two addresses into the ViewData.
In your main view, call your two Address subviews like this:
您可以将 ViewModel
表单元素的值映射到 ViewModel 的正确成员(如果它们具有以下形式)
没有简单而优雅的方法可以从 StreetAddress1 到 ShippingAddress.StreetAddress1。
我的地址模型具有以下形式:
我将 InstanceName 设置为属性的名称 (ShippingAddress)。
然后在这个表单中定义了表单元素
ascx 的地方看起来并不常见。 您有什么理由不将其放入 Shared 并通过 访问它
?
You can have a ViewModel
The values of formelements are mapped to the right Member of the ViewModel if they have the form
There is no easy and elegant way to come from StreetAddress1 to ShippingAddress.StreetAddress1.
My address model has the form:
I set the InstanceName to the Name of the property (ShippingAddress).
Then the form elements are defined in this form
The place of the ascx looks uncommon. Any reason why you dont put it in Shared and access it by
?