C# MVC 4参数名称和视图模型中的继承

C# MVC 4参数名称和视图模型中的继承,c#,asp.net-mvc,asp.net-mvc-4,model-binding,C#,Asp.net Mvc,Asp.net Mvc 4,Model Binding,我曾试图寻找解决我问题的办法,但我失败了 我的Asp.NET MVC 4 Web应用程序中有这样一个模型: public class ModelBase { public string PropertyOne { get; set; } public string PropertyTwo { get; set; } } public class InheritedModelOne : ModelBase { public string PropertyThree { get; se

我曾试图寻找解决我问题的办法,但我失败了

我的Asp.NET MVC 4 Web应用程序中有这样一个模型:

public class ModelBase
{
  public string PropertyOne { get; set; }
  public string PropertyTwo { get; set; }
}

public class InheritedModelOne : ModelBase
{
  public string PropertyThree { get; set; }
}

public class InheritedModelTwo : ModelBase
{
  public string PropertyFour { get; set; }
}
我的控制器中有两个操作:

public ActionResult ActionOne([ModelBinder(typeof(MyModelBinder))]ModelBase formData)
{
  ...
}

public ActionResult ActionTwo(InheritedModelTwo inheritedModelTwo)
{
  ...
}
我的问题是,当我在ActionTwo的Action参数中使用名称“inheritedModelTwo”时,属性PropertyFour已正确绑定,但当我在ActionTwo的Action参数中使用名称formData时,属性PropertyOne和PropertyTwo已正确绑定,但属性yFour已正确绑定。我要做的是在发布表单时正确绑定我的ActionTwo方法的InheritedModelTwo参数的所有三个属性

更多信息:

  • 这篇文章来自同一个JQuery请求
  • 来自post的数据在这两种情况下是相同的
  • 这个问题唯一的区别是Action2的参数名
  • 在ActionTwo的参数中输入不同的名称只会使ModelBase属性绑定
  • 对不起,我的英语真的很差

  • Tks.

    如果我理解正确

    您试图做的是:使用基本对象类型映射/绑定从基本对象继承的对象

    这将不起作用,因为继承只在一个方向上起作用

    ..因此,您必须使用继承模型类型作为参数类型

    public class ModelBase
    {
        public string PropertyOne { get; set; }
        public string PropertyTwo { get; set; }
    }
    
    public class InheritedModelOne : ModelBase
    {
        public string PropertyThree { get; set; }
    }
    
    public class testObject
    { 
        [HttpPost]
        public ActionResult ActionOne(ModelBase formData)
        {
            formData.PropertyOne = "";
            formData.PropertyTwo = "";
    
            // This is not accessible to ModelBase
            //modelBase.PropertyThree = "";
    
            return null;
        }
        [HttpPost]
        public ActionResult ActionOne(InheritedModelOne inheritedModelOne)
        {
            // these are from the Base
            inheritedModelOne.PropertyOne = "";
            inheritedModelOne.PropertyTwo = "";
    
            // This is accessible only in InheritingModel
            inheritedModelOne.PropertyThree = "";
    
            return null;
        }
    
    }
    

    你能发表你的观点吗?您是否使用@Html.textbox作为帮助程序?它应该对你有用。另一个技巧是,使用fiddler或Firebug,查看发送到控制器的内容。您可以将整个视图与jquery请求放在一起吗?然后我们可以测试您所说的内容。把它放在你的帖子上。是的,我使用@Html.TextBoxFor,记住我在这两种情况下的帖子数据是相同的,当我更改ActionTwo的参数名时,不同的属性被绑定而没有视图更改。请,使用jquery代码发布视图……如果希望将基类以外的内容传递到第一个操作中,则必须在
    MyModelBinder
    类中执行一些特殊操作。