ASP.NET MVC:模型绑定复杂类型

编程入门 行业动态 更新时间:2024-10-12 16:26:37
本文介绍了ASP.NET MVC:模型绑定复杂类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在绑定到对象列表时,绑定对象时遇到问题. 在工具更新中使用Mvc3.1.

I'm having problems binding to an object while binding to a List of objects works. Using Mvc3.1 with Tools update.

当绑定到类Form时,HttpPost函数将接收正确的模型. 绑定到FormViewModel时,HttpPost函数会收到一个空模型.

When binding to the class Form, the HttpPost-function recieves the correct model. When binding to the FormViewModel, the HttpPost-function recieves an empty model.

绑定包含其他模型的模型时有任何限制吗?

Are there any restrictions when binding Models containing other models?

public class FormViewModel { public Form Form { get; set; } } public class Form { public List<Section> Sections { get; set; } } public class Section { public List<Question> Questions { get; set; } } public class Question { public int Id { get; set; } public string Description { get; set; } }

推荐答案

输入元素的name属性是活页夹用作魔术的上下文.我的猜测是您的视图包含以下内容:

The name attribute of your input elements is what the binder uses as context for doing its magic. My guess is that your view contains something like this:

@model Form @Html.EditorFor(m => m.Sections)

您的发布方法如下:

[HttpPost] public ActionResult Function(FormViewModel formViewModel) { // ... }

如果您将视图更改为:

@model FormViewModel @Html.EditorFor(m => m.Form.Sections)

然后执行get操作以返回FormViewModel的实例,它可能会正常工作.帮助程序将使用lambda表达式的主体来创建输入元素的名称.在这种情况下,它将创建类似Form.Sections[0].Field的内容.然后,模型绑定程序可以在Form.Sections []上拾取并正确初始化FormViewModel.

And your get action to return an instance of FormViewModel, it would probably work just fine. The helpers will use the body of the lambda expression to create the name of the input element. In this case, it will create something like Form.Sections[0].Field. Then, the model binder is able to pick up on Form.Sections[] and properly initialize the FormViewModel.

更多推荐

ASP.NET MVC:模型绑定复杂类型

本文发布于:2023-11-16 15:24:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1605496.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   模型   类型   ASP   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!