ASP.NET MVC 中与嵌套子模型和 PartialView 的模型绑定
我有以下类型和类:
namespace MVC.Models
public class Page
{
public EditableContent Content {get; set; }
}
public class EditableContent
{
public TemplateSection SidebarLeft {get; set; }
public TemplateSection SidebarRight {get; set; }
}
我想在 Edit.aspx
视图中编辑 Page
实例。由于 EditableContent
也附加到其他模型,因此我有一个名为 ContentEditor.ascx
的 PartialView
,它是强类型的并采用 的实例EditableContent
并呈现它。
渲染部分一切正常,但当我发布时 - 我的 ContentEditor
内的所有内容都未绑定 - 这意味着 Page.Content
为 null
。
在 PartialView 上,我使用强类型 Html Helpers 来执行此操作:
<%= Html.HiddenFor(m => m.TemplateId) %>
但是因为由 ContentEditor.ascx
呈现的表单上的输入元素没有获取 Content
前缀它的 id
属性 - 值未绑定到 Page
。
我尝试使用松散类型的帮助器来克服这个问题:
<%= Html.Hidden("Content.TemplateId", Model.TemplateId) %>
当我处理一个 List
的属性时,它会变得非常难看。然后我必须手动渲染集合索引。
我应该将 Page 和 EditableContent 作为控制器操作的参数吗?:
public ActionResult Edit(Page page, EditableContent content) { ... }
我缺少什么?
I have the following types and classes:
namespace MVC.Models
public class Page
{
public EditableContent Content {get; set; }
}
public class EditableContent
{
public TemplateSection SidebarLeft {get; set; }
public TemplateSection SidebarRight {get; set; }
}
I want to edit the Page
instance in my Edit.aspx
View. Because EditableContent
is also attached to other models, I have a PartialView
called ContentEditor.ascx
that is strongly typed and takes an instance of EditableContent
and renders it.
The rendering part all works fine, but when I post - everything inside my ContentEditor
is not binded - which means that Page.Content
is null
.
On the PartialView, I use strongly typed Html Helpers to do this:
<%= Html.HiddenFor(m => m.TemplateId) %>
But because the input elements on the form that are rendered by ContentEditor.ascx
does not get the Content
prefix to its id
attribute - the values are not binded to Page
.
I tried using loosely typed helpers to overcome this:
<%= Html.Hidden("Content.TemplateId", Model.TemplateId) %>
And when I'm dealing with a property that is a List<T>
of something it gets very ugly. I then have to render collection indexes manually.
Should I put both Page and EditableContent as parameters to the controller action?:
public ActionResult Edit(Page page, EditableContent content) { ... }
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议您使用
EditorFor
帮助器模型:
Views/Home/Index.aspx:
Views/Shared/EditorTemplates/EditableContent.ascx:
最后是Controller/HomeController:
I would suggest you to use the
EditorFor
helperModel:
Views/Home/Index.aspx:
Views/Shared/EditorTemplates/EditableContent.ascx:
And finally Controller/HomeController: