Gustavo
Gustavo

Reputation: 735

MVC SelectList is empty in model when Posting back to Controller

This is my model:

[Display(Name = "Company")]
public int CompanyId { get; set; }

public SelectList Companies { get; set; }

Setting Data for view

    [HttpGet]
    [AllowAnonymous]
    public ActionResult Index()
    {
        var model = new Ticket
        {
            Companies = new SelectList(new List<SelectListItem> { new SelectListItem { Text = "0", Value = "0" } }, "Value", "Text")
        };
        return View(model);
    }

The View:

    <div class="form-group">
        @Html.LabelFor(m => m.CompanyId, new { @class = "col-md-6 col-md-pull-1 control-label" })
        <div class="col-md-3 col-md-pull-1">
            @Html.DropDownListFor(m => m.CompanyId, Model.Companies, new { @class = "selectpicker form-control" })
        </div>
    </div>

Results:

This is the result

How can i get the SelectList to be posted back to the Controller so i dont have to keep populating it?

Upvotes: 2

Views: 1356

Answers (1)

Escobar5
Escobar5

Reputation: 4082

Model.Companies wont be binded because is not in the Form, the ModelBinder is looking for an input in the Form or a querystring value with the name of the property (in this case Companies) but you don´t have one in the view with that name, on the contrary, you have a field with the name CompanyId, that´s why the property CompanyId is binded.

A good way to save your Companies list and get it in the Post action is to use TempData, with TempData you can save an item in an action, and it´ll be available to the next action. Is like Session, but just for one Request.

Upvotes: 1

Related Questions