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

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

问题描述

我有2个车型在我的示例MVC 3应用程序, SimpleModel ComplexModel ,如下图所示:

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" />
}

提交形式,状态字段进入随机值后,该值是不绑定到我的模型。在状态字段是 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" />
}

然后把简单部分内〜/查看/共享/ EditorTemplates / SimpleModel.cshtml 或内部〜/查看/主页/ EditorTemplates / SimpleModel.cshtml ,其中首页是控制器的名称:

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)

当然,如果你preFER有部分在一些特殊的位置,而不是遵守的规则(为什么你会吗?),你可以指定位置:

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天全站免登陆