mvc.net 如何编辑嵌套视图模型类
我有以下嵌套视图模型类...
public class CustomerModel
{
public string name;
public Address mailingAddress;
public Address billingAddress;
}
public class Address
{
public string line1;
public string city;
public string country;
}
我希望有一些自动方法来创建编辑页面,但我尝试和阅读的所有内容都表明框架和代码生成仅处理视图模型中的顶级属性。 “name”属性是在视图和操作中生成的唯一属性,只有“name”属性填充了保留为空的地址。
[HttpPost]
public ActionResult Edit(CustomerModel model)
但是,如果我手动添加地址的输入框(通过部分视图)并切换到该操作的 FormCollection 签名,我会在屏幕上输入适当的地址值。
除了创建我自己的函数以从 FormCollection 转换为 CustomerModel 之外,是否有任何简单的解决方案?
I have the following nested viewmodel class...
public class CustomerModel
{
public string name;
public Address mailingAddress;
public Address billingAddress;
}
public class Address
{
public string line1;
public string city;
public string country;
}
I was hoping that there is some automated way to create an edit page, but everything that I've tried and read indicates that the framework and code-generates only handle top level properties in your viewmodel. The 'name' property is the only one generated in the view and in the action, it is only the 'name' property that is populated with the addresses being left as null.
[HttpPost]
public ActionResult Edit(CustomerModel model)
however, if i manually add input boxes for the address (through partial views) and switch over to the FormCollection signature for the action, i get the appropriate address values entered on the screen.
is there any easy solution for this other than creating my own function to convert from FormCollection to CustomerModel?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在这里使用编辑器模板吗?基本上,您创建一个强类型的部分视图(地址是您案例中的类型),将其存储在特定文件夹(/Views/Shared/EditorTemplates)中,并且每当为该数据类型的成员呈现编辑器时,部分视图而是自动渲染。因此,调用
Html.EditorFor(model => model.mailingAddress)
会渲染部分视图。我想我第一次读到这一点是在我寻找一些日期时间验证时。看看这个 链接,也许你的部分视图会有一些
Html.EditorFor(model => model.line1)
和Html.EditorFor(model => model.city)
这并不会让一切变得超级自动化,但它有助于将来编辑地址等数据类型。
Could you use an editor template here? Basically, you create a strongly typed partial view (Address is the type in your case), store it in a specific folder (/Views/Shared/EditorTemplates) and whenever an editor is rendered for a member of that data type, the partial view is automagically rendered instead. So, calling
Html.EditorFor(model => model.mailingAddress)
renders the partial view instead.I think the first place I read about this was when I was looking for some DateTime validation. Check out this link, and maybe your partial view will have some
Html.EditorFor(model => model.line1)
's andHtml.EditorFor(model => model.city)
'sThis does not make everything super-automatic, but it helps with the future editing of data types like Address.