Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC SelectList in ViewModel

I'm working in ASP.NET MVC 5 (but this most likely applies to previous versions also). Best way to ask this question is to show you the code:

Here is the View Model:

public class PersonCreateViewModel
{
    public SelectList cities {get; set;}
    public String Name { get; set; }
    public String Address { get; set; }

}

Here is the http Post method from the controller:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(PersonCreateViewModel viewmodel)
{

    if (ModelState.IsValid)
    {
        //Add to database here and return

    }

    //return back to view if invalid db save
    return View(person);
}

Here is the View:

<div class="form-group">
        @Html.LabelFor(model => model.person.name, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
        @Html.EditorFor(model => model.person.name)
        @Html.ValidationMessageFor(model => model.person.name)
    </div>
</div>

<div class="form-group">
        @Html.LabelFor(model => model.person.address, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
        @Html.EditorFor(model => model.person.address)
        @Html.ValidationMessageFor(model => model.person.address)
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(model => model.person.CityID, "CityID", new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("cities")
        @Html.ValidationMessageFor(model => model.person.CityID)
    </div>
</div>

When the user clicks submit, the following error message is in the browser: "No parameterless constructor defined for this object. "

I think it has something to do with the fact that I have a SelectList in my ViewModel. I think when the view passes the model back to the controller on form submission, it calls the constructor for the SelectList, but there is no parameterless constructor for SelectList. I'm not sure how to proceed. Any help is appreciated!!

like image 257
carlg Avatar asked Dec 04 '13 22:12

carlg


1 Answers

I've always had better luck using IEnumerable

public class PersonCreateViewModel
{
    public IEnumerable<SelectListItem> cities {get; set;}
    public int CityId { get; set; }
    public String Name { get; set; }
    public String Address { get; set; }
}

Also, you are going to need a property on the view model to capture the selected value like CityId.

Then you can use:

Html.DropDownListFor(m => m.CityId, Model.cities)
like image 156
Mark Olsen Avatar answered Oct 14 '22 17:10

Mark Olsen