Search code examples
asp.net-mvcdrop-down-menufindby

How to make dropdownlist show a selected value in asp.net mvc?


I have an edit page with a Html.DropDownList in it....I cant show the dropdownlist value it always shows up with Select instead i want to make the dropdown show an item as selected based on a model value say Model.Mes_Id... Any suggestion how it can be done...

       <p>
            <label for="MeasurementTypeId">MeasurementType:</label>
         <%= Html.DropDownList("MeasurementType", // what should i give here?)%>
            <%= Html.ValidationMessage("MeasurementTypeId", "*") %>
        </p>

EDIT: It has the list items but i want to show a value selected in the edit view...

   public ActionResult Edit(int id)
    {
        var mesurementTypes = consRepository.FindAllMeasurements();
        ViewData["MeasurementType"] = mesurementTypes;
        var material = consRepository.GetMaterial(id);
        return View("Edit", material);
    }

My repository method,

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

Solution

  • Set the selected item when you create the IEnumerable<SelectListItem>.

    Personally I would create a specialized viewmodel for the form but going by your code, do something like:

    public ActionResult Edit(int id)
    {
        //Put this first
        var material = consRepository.GetMaterial(id);
        //pass in your selected item
        var mesurementTypes = consRepository.FindAllMeasurements(material.MeasurementTypeId);
        ViewData["MeasurementType"] = mesurementTypes;
    
        return View("Edit", material);
    }
    

    Then change your repository method to something like:

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

    HTHs,
    Charles