Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What am i doing wrong with asp.net-mvc dropdownlist?

I use a dropdownlist in one of my create.aspx but it some how doesnt seem to work...

public IEnumerable<SelectListItem> FindAllMeasurements()
    {
        var mesurements = from mt in db.MeasurementTypes
                          select new SelectListItem
                          {
                             Value = mt.Id.ToString(),
                             Text= mt.Name
                          };
        return mesurements;
    }

and my controller,

 public ActionResult Create()
    {
      var mesurementTypes = consRepository.FindAllMeasurements().AsEnumerable();
     ViewData["MeasurementType"] = new SelectList(mesurementTypes,"Id","Name");
     return View();
    } 

and my create.aspx has this,

<p>
  <label for="MeasurementTypeId">MeasurementType:</label>
    <%= Html.DropDownList("MeasurementType")%>
     <%= Html.ValidationMessage("MeasurementTypeId", "*") %>
   </p>

When i execute this i got these errors,

DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a 
 property with the name 'Id'.
like image 785
ACP Avatar asked May 03 '10 05:05

ACP


1 Answers

In your controller you are creating a new SelectList from IEnumerable<SelectListItem> which is not correct because you've already specified the Value and Text properties.

You have two options:

public ActionResult Create()
{
    var mesurementTypes = consRepository.FindAllMeasurements();
    ViewData["MeasurementType"] = mesurementTypes;
    return View();
}

or:

public ActionResult Create()
{
    ViewData["MeasurementType"] = new SelectList(db.MeasurementTypes, "Id", "Name");
    return View();
}

There's also a third and preferred way using strongly typed view:

public ActionResult Create()
{
    var measurementTypes = new SelectList(db.MeasurementTypes, "Id", "Name");
    return View(measurementTypes);
}

and in the view:

<%= Html.DropDownList("MeasurementType", Model, "-- Select Value ---") %>
like image 61
Darin Dimitrov Avatar answered Nov 08 '22 01:11

Darin Dimitrov