本文介绍了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:模型绑定复杂类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 20:32