Kupi
Kupi

Reputation: 933

Passing Model via dropDownListFor() from view to controller

I am trying to pass a Model from my view to my controller using dropDownListFor. After choosing something from the list it sends the model to my controller but it's content NULL.

This is what i have for the Model

public class Model
{
    public int ModelId { get; set; }
    [Required]
    public string Name { get; set; }
}

This is what my ViewModel looks like

public class ModelVM
{
    public List<Model> Models;
    public Model SelectModel { get; set; }
    public IEnumerable<SelectListItem> ModelItems
    {
        get { return new SelectList(Models, "ModelId", "Name"); }
    }
}

The controller when i put data in the ViewModel looks like this

    public ActionResult Index()
    {
        ModelVM modelVM= new ModelVM()
        {
            Models = manager.GetAllModels().ToList()
        };
        return View(modelVM);
    }

Finally this is what i have in the View for the dropDownList

    @using (Html.BeginForm("Home", "Home", FormMethod.Post))
    {
        @Html.DropDownListFor(model => model.SelectModel, Model.ModelItems)
        <input type="submit" value="Go" />
    }

So this is supposed to send Model to my controller. But when i check the content of the passed Model in the controller, everything is NULL which isn't supposed to be because when i debug the view and check for the content of ModelItems, everything in the ModelItems is there.

Here is when i check the content of the passed Model

 public ActionResult Home(Model model) <<<<<<<<<< Content == NULL
    {
        return View();
    }

Upvotes: 1

Views: 2975

Answers (2)

user3559349
user3559349

Reputation:

A <select> element on posts back a single value. Html has no concept of what your c# Model class is so you cannot bind to a complex object. You need to bind to the ModelId property of Model. Your view model should be

public class ModelVM
{
  [Display(Name = "Model")]
  public int SelectedModel { get; set; }
  public SelectList ModelItems { get; set ;}
}

and in the controller

public ActionResult Index()
{
    ModelVM modelVM = new ModelVM()
    {
        ModelItems = new SelectList(manager.GetAllModels(), "ModelId", "Name")
        // SelectedModel = ? if you want to preselect an item
    };
    return View(modelVM);
}

and in the view

@Html.LabelFor(m => m.SelectedModel)
@Html.DropDownListFor(m => m.SelectedModel, Model.ModelItems)

and in the post method your model will be correctly bound with the ID of the selected model

Upvotes: 3

ozz
ozz

Reputation: 5366

Trying passing in type ModelVM to the Home action as that is the type being passed to Index view.

Instead of model.SelectModel in the drop-down declaration, you only need an int ID to capture which ID is selected.

Upvotes: 0

Related Questions