Hanna
Hanna

Reputation: 10781

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. 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;" />
    }

Upvotes: 0

Views: 159

Answers (1)

scartag
scartag

Reputation: 17680

@Model appears to be a complex type so you cannot assign to as the value of the input field.

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.

Replace this

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

with

@Html.EditorFor(model => model)

Upvotes: 1

Related Questions