默认的模型绑定的情况下,无法正常工作时,模型中包含的模型 [英] default model binding does not work in case when model contains a model

查看:139
本文介绍了默认的模型绑定的情况下,无法正常工作时,模型中包含的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的模型。

public class InfoModel
    {
        public NameModel Name { get; set; }
        public string Phone { get; set; }
    }

public class NameModel
    {
        public string FirstName { get; set; }
        public string LastName  { get; set; }

        public NameModel(string first, string last)
        {
            this.FirstName = first;
            this.LastName = last;
        }
    }

然后,我有一个部分只查看如下显示的名字

Then I have a partial View just for displaying names as follows

@model MyTestApp.Models.NameModel

@Html.LabelFor( m => m.LastName) 
@Html.TextBoxFor( m => m.LastName)       
<br />
@Html.LabelFor( m => m.FirstName) 
@Html.TextBoxFor( m => m.FirstName)       

再有就是对ShowInfo视图

Then there is a view for ShowInfo

@model MyTestApp.Models.InfoModel

@using (@Html.BeginForm())
{
    @Html.Partial("ShowName", Model.Name)
    <br />
    @Html.LabelFor( m => m.Phone) 
    @Html.TextBoxFor(m => m.Phone)
    <br />
   <input type="submit" value="Submit Info" />
}

现在用户提交的任何信息,跟踪控制方法被称为

Now user submit any info, following controller method is called

 [HttpPost]
 public ActionResult ShowInfo(InfoModel model)
 {
    ...
 }

问题是当我检查模式的价值,手机是不错,但名称为null。任何想法如何使它工作?

Problem is when i inspect the value of model, phone is fine but name is null. Any ideas how to make it work?

推荐答案

DefaultModelBinder 类使用 Activator.CreateInstance(typeToCreate)内部创建模型类。你的 NameModel 类不到风度有一个默认的构造函数,以便在 DefaultModelBinder 不能实例化。所以,如果你添加默认的构造函数它应该工作。

The DefaultModelBinder class uses Activator.CreateInstance(typeToCreate) internally to create the model classes. Your NameModel class dosn't have a default constructor so the DefaultModelBinder can't instantiate it. So if you add the default constructor it should work.

编辑
它不会工作局部视图,你需要使用一个EditorTemplate代替:结果
名为 EditorTemplates 创建视图文件夹下的文件夹,把你的ShowName.cshtml那里添加在你的主视图中使用:

EDIT It won't work Partial view you need to use an EditorTemplate instead:
Create a folder under your view folder with the name EditorTemplates and put your ShowName.cshtml there add in your main view use:

@using(Html.BeginForm())
{
    @Html.EditorFor(m => m.Name, "ShowName")
    ...

这篇关于默认的模型绑定的情况下,无法正常工作时,模型中包含的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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