简体   繁体   English

将模型发布回ASP.NET MVC3中的控制器

[英]Posting a model back to controller in ASP.NET MVC3

I'm trying to post a model back to the controller but for some reason the controller always gets NULL back. 我正在尝试将模型发布回控制器,但是由于某些原因,控制器总是返回NULL。 I know I'm doing something really obviously wrong. 我知道我在做某些明显错误的事情。 What is it? 它是什么?

However if I post back a specific attribute from that model, it works just fine. 但是,如果我从该模型发回特定属性,则可以正常工作。

Controller: 控制器:

[HttpPost]
        public void MyAction(Company company)
        {
            System.Diagnostics.Debug.WriteLine("STUFF:" + company.dbName);
            if(company.CompanyOptions!=null)foreach (var item in company.CompanyOptions.CompanyLicenseOptions.CompanyLicenseOptionsList) System.Diagnostics.Debug.WriteLine("STUFF:" + item);
            else System.Diagnostics.Debug.WriteLine("STUFF IS NULL");
        }

View: 视图:

@model Domain.Entities.Company
    @using (Html.BeginForm("MyAction", "Controller", FormMethod.Post))
    {
        foreach (var licensedFeature in Model.CompanyOptions.CompanyLicenseOptions.CompanyLicenseOptionsList)
        {
            @Html.CheckBox(licensedFeature.LicenseName, licensedFeature.IsLicensed, checkboxHtmlAttributes);
            @licensedFeature.LicenseName                                                                                          
        } 
        <input type="hidden" name="company" value="@Model"/>
        <input id="submit_licenses" type="submit" style="display:none;" />
    }

@Model appears to be a complex type so you cannot assign to as the value of the input field. @Model似乎是一个复杂的类型,因此您不能将其指定为输入字段的值。

The best you can do is use an @Html.EditorFor to generate the required html fields for the model and this will ensure that they are posted back as the Company object. 最好的办法是使用@Html.EditorFor生成模型所需的html字段,这将确保它们作为Company对象发回。

Replace this 取代这个

<input type="hidden" name="company" value="@Model"/>

with

@Html.EditorFor(model => model)

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

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