复杂模型和局部视图 - ASP.NET MVC 3 中的模型绑定问题 [英] Complex models and partial views - model binding issue in ASP.NET MVC 3

查看:30
本文介绍了复杂模型和局部视图 - ASP.NET MVC 3 中的模型绑定问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的示例 MVC 3 应用程序中有 2 个模型,SimpleModelComplexModel,如下所示:

I have 2 models in my sample MVC 3 application, SimpleModel and ComplexModel, shown below:

public class SimpleModel
{
    public string Status { get; set; }
}

public class ComplexModel
{
    public ComplexModel()
    {
        Simple = new SimpleModel();
    }

    public SimpleModel Simple{ get; set; }
}

我已经为这个模型定义了视图:

I have defined views for this models:

_SimplePartial.cshtml:

@model SimpleModel

@Html.LabelFor(model => model.Status)
@Html.EditorFor(model => model.Status)

Complex.cshtml:

@model ComplexModel

@using (Html.BeginForm()) {

    @Html.Partial("_SimplePartial", Model.Simple)
    <input type="submit" value="Save" />
}

提交表单后,在 Status 字段中输入随机值,该值未绑定到我的模型.当我在控制器操作中检查模型时,Status 字段为 NULL:

After submitting form, with random value entered in Status field, the value is not binded to my model. The Status field is NULL when I'm checking the model in my controller action:

[HttpPost]
public ActionResult Complex(ComplexModel model)
{
    // model.Simple.Status is NULL, why ?
}

为什么没有绑定?我不想继承模型.我是否必须为这种简单的情况编写自定义模型绑定器?

Why is it not binded ? I don't want to inherit models. Do I have to write my custom model binders for such simple case ?

问候.

推荐答案

代替:

@Html.Partial("_SimplePartial", Model.Simple)

我建议您使用编辑器模板:

I would recommend you using Editor templates:

@model ComplexModel
@using (Html.BeginForm()) 
{
    @Html.EditorFor(x => x.Simple)
    <input type="submit" value="Save" />
}

然后将简单的部分放在 ~/Views/Shared/EditorTemplates/SimpleModel.cshtml~/Views/Home/EditorTemplates/SimpleModel.cshtml 中,其中 Home 是您的控制器的名称:

and then put the simple partial inside ~/Views/Shared/EditorTemplates/SimpleModel.cshtml or inside ~/Views/Home/EditorTemplates/SimpleModel.cshtml where Home is the name of your controller:

@model SimpleModel
@Html.LabelFor(model => model.Status)
@Html.EditorFor(model => model.Status)

当然,如果您更喜欢将部分放在某个特殊位置而不遵循约定(为什么要这样做?),您可以指定位置:

Of course if you prefer to have the partial in some special location and not follow the conventions (why would you?) you could specify the location:

@Html.EditorFor(x => x.Simple, "~/Views/SomeUnexpectedLocation/_SimplePartial.cshtml")

那么一切都会按预期进行.

then everything will come into place as expected.

这篇关于复杂模型和局部视图 - ASP.NET MVC 3 中的模型绑定问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆