mvc.net 如何编辑嵌套视图模型类

发布于 2024-09-19 01:30:33 字数 600 浏览 7 评论 0原文

我有以下嵌套视图模型类...

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦境 2024-09-26 01:30:33

您可以在这里使用编辑器模板吗?基本上,您创建一个强类型的部分视图(地址是您案例中的类型),将其存储在特定文件夹(/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 and Html.EditorFor(model => model.city)'s

This does not make everything super-automatic, but it helps with the future editing of data types like Address.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文