简体   繁体   English

ASP.NET MVC 2 Model子类始终为null

[英]ASP.NET MVC 2 Model subclass always null

I have a problem with passing values from model to controller, let's say i have two classes: 我在将值从模型传递到控制器时遇到问题,假设我有两个类:

public class Model
{
    public string Name { get; set; } 
    public SubClass Value { get; set; } 
}
public class SubClass
{
    public string Value1 { get; set; }
    public string Value2 { get; set; }
}

in view, I'm assigning values to Model's property value of type SubClass like this : 在视图中,我正在为SubClass类型的Model的属性值分配值,如下所示:

<%: Html.TextBoxFor(model => model.Value.Value1) %> 

<%: Html.TextBoxFor(model => model.Value.Value1) %>

The view is passing to controller only the Name property of Model, the Value property always stays null. 该视图仅将Model的Name属性传递给控制器​​,Value属性始终保持为null。 Any suggestions ? 有什么建议么 ?

This is because by default, the MVC model binder won't pass (complex ie non-primitive types) sub-types back to the controller on a post. 这是因为默认情况下,MVC模型联编程序不会将(复杂的,即非原始类型的)子类型传递回帖子上的控制器。 Your property public SubClass Value { get; set; } 您的媒体资源的public SubClass Value { get; set; } public SubClass Value { get; set; } public SubClass Value { get; set; } is a complex type (a class you've written called SubClass). public SubClass Value { get; set; }是一种复杂类型(您编写了一个名为SubClass的类)。

You need to write a custom model binder for this, to tell MVC how to post sub-class(es) back with your model. 您需要为此编写一个自定义模型绑定程序,以告诉MVC如何将子类发布回您的模型。 Here's some great articles on custom model binding to help you get to where you need to be. 这是有关自定义模型绑定的一些出色文章,可帮助您到达所需的位置。

http://odetocode.com/Blogs/scott/archive/2009/04/27/12788.aspx http://odetocode.com/Blogs/scott/archive/2009/04/27/12788.aspx

http://odetocode.com/Blogs/scott/archive/2009/05/05/12801.aspx http://odetocode.com/Blogs/scott/archive/2009/05/05/12801.aspx

In your controller you have to get the model : 在您的控制器中,您必须获取模型:

[httpost]
public void action(Model model)
{
   //get your subClass values
    string s = model.Value.Value1;         
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM