简体   繁体   English

MVC HttpPost强类型模型null

[英]MVC HttpPost strongly typed Model null

View Model looks like this: View Model看起来像这样:

public class AsmenysInfoViewModel2
{
    public asmenys_info Asmenys_info { get; set; }
    public List<miestai> Miestai { get; set; }
    public string Test { get; set; }
}

And there are two actions. 有两个动作。 Get and Post. 获取和发布。

    public ActionResult Index(long? id)
    {

        var model = new AsmenysInfoViewModel2();
        model.Test = "Test";
        model.Asmenys_info = BllFactory.DalFactory.AsmenysInfoDal.GetById(id.Value);
        return View(model);
    }
    [HttpPost]
    public ActionResult Index(AsmenysInfoViewModel2 asmenys_info)
    {
        var model = asmenys_info;
        return View(model);
    }

And my view looks like this: 我的观点看起来像这样:

@model MODELS.AsmenysInfoViewModel2
@{
    ViewBag.Title = "Index";
}
@using (Html.BeginForm("Index", "AsmenysInfo", FormMethod.Post))
{
    @Html.ValidationSummary()
    @Html.TextBoxFor(m => m.Asmenys_info.adresas)       

    <input type="submit" value="Išsaugoti" />
}

Doesn't matter if I use EditorFor or TextBoxFor - result is same. 如果我使用EditorFor或TextBoxFor无关紧要 - 结果相同。 My model property "Asmenys_info" on posting is always null. 发布时我的模型属性“Asmenys_info”始终为null。 If my class AsmenysInfoViewModel2 would not contain asmenys_info type property and would contain only "string, int etc" (no strongly typed) - it would work. 如果我的类AsmenysInfoViewModel2不包含asmenys_info类型属性并且只包含“string,int etc”(没有强类型) - 它会起作用。 My question is : 我的问题是:

How to post View Model which has strongly typed property which on posting would not be null? 如何发布具有强类型属性的View Model,在发布时不会为null?

Your model has a property named Asmenys_info and the parameter in your POST method is also named asmenys_info . 您的模型具有名为Asmenys_info的属性,POST方法中的参数也名为asmenys_info Internally the DefaultModelBinder reads the values of the form data which includes a value for Asmenys_info and attempts to set property Asmenys_info to that value but it fails because there is no conversion from a string to a complex object. 在内部, DefaultModelBinder读取包含Asmenys_info值的表单数据的值,并尝试将属性Asmenys_info设置为该值但由于没有从string到复杂对象的转换而失败。

Change the name of the parameter to anything other than a name of a property in your model and it will bind fine, for example 例如,将参数的名称更改为模型中属性名称以外的任何名称,它将绑定正常

[HttpPost]
public ActionResult Index(AsmenysInfoViewModel2 model)

Change the below line with another object name 使用其他对象名称更改以下行

 public ActionResult Index(AsmenysInfoViewModel2 asmenys_info)

in above method use any other name of object instead of asmenys_info . 在上面的方法中使用对象的任何其他名称而不是asmenys_info

because while mvc framework map your model with object there is confution in asmenys_info and Asmenys_info property of AsmenysInfoViewModel2 class. 因为虽然mvc框架使用对象映射模型,但AsmenysInfoViewModel2类的asmenys_info和Asmenys_info属性存在混淆。

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

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