9

I'm using @html.EditorFor to render my model in edit mode, and a dropdownlist is not rendered.

Here's my ViewModel:

     public class RiskAutoViewModel
     {
       public RiskAutoViewModel()
       {
         VehicleMakeList = new SelectList(new List<VehicleMake>() { new VehicleMake() { Id = 1, Name = "Renault" }, new VehicleMake() { Id = 2, Name = "Peugeot" } });
       }


    public int NoClaimsDegree { get; set; }

    public int VehicleValue { get; set; }

    public int EngineCapacity { get; set; }

    public int VehicleMake { get; set; }

    public SelectList VehicleMakeList { get; set; }
  }

VehicleMake is rendered as a textbox and VehicleMakeList is not rendered at all. What I'd like is to render a dropdownlist containing the list of VehicleMake and set its value to the one of VehicleMake.

When the model is saved, VehicleMake should be set to the value of the selected item in the list.

How can I do that ?

EDIT

Since I can't type any code in the comment boxes below, I'll write a follow up here.

I ended up creating a EditorTemplate such as:

<div class="editor-label">
    @Html.LabelFor(model => model.VehicleMakeList)
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.VehicleMake, Model.VehicleMakeList)
    @Html.ValidationMessageFor(model => model.VehicleMake)
</div>

And now my ViewModel looks like this:

[Required]
[ScaffoldColumn(false)]
public int VehicleMake { get; set; }

[Display(Name = "Marque", Prompt = "Marque", Description = "Renseigne la marque du véhicule")]
public SelectList VehicleMakeList { get; set; }

Now this leads me to another question (maybe I should as in a different thread) but I actually have TWO dropdowns in that View. And the items in the second dropdown are basically dynamic and they depend on the item selected in the first dropdown. This is dead easy to do with AJAX but with MVC I'm lost. How do people do that usually ?

Sam
  • 13,934
  • 26
  • 108
  • 194
  • And just a heads up for you, if you decide to follow the `@Html.EditorFor()` with a `@Html.DropDownlistFor`, you're going to have issues with binding the VehicleMake property with the dropdown selection, as it's value will be determined by the textbox redered by the `EditorFor()` – Forty-Two Feb 01 '13 at 21:34
  • edited my answer with the simplest solution – Forty-Two Feb 01 '13 at 21:38

4 Answers4

11

Unfortunately, there is no built in support for drop down lists in the editor for templates. You can either write your own editor template, or use the html helper method @Html.DropDownListFor() in your view.

Darin Dimitrov's answer to this question can walk you through the process of building an editor template for drop down lists, if you are so inclined.

The quickest way to get this working would be to do this in your view:

@Html.EditorFor(model => model.NoClaimsDegree)
@Html.EditorFor( model => model.VehicleValue )
@Html.EditorFor( model => model.EngineCapacity )
@Html.DropDownListFor( model => model.VehicleMake, Model.VehicleMakeList, "Select a make" )
Community
  • 1
  • 1
Forty-Two
  • 7,535
  • 2
  • 37
  • 54
  • I ended up doing similar in a EditorTemplate (why can't I type code in this comment box, it's annoying...)
    @Html.LabelFor(model => model.VehicleMakeList)
    @Html.DropDownListFor(model => model.VehicleMake, Model.VehicleMakeList) @Html.ValidationMessageFor(model => model.VehicleMake)
    – Sam Feb 01 '13 at 22:06
10

I think the model for dropdownlist should be:

public List<System.Web.Mvc.SelectListItem> VehicleMakeList {get; set;}

And initialized like:

VehicleMakeList = new List<System.Web.Mvc.SelectListItem>() 
{ 
   new SelectListItem { Value = "1", Text = "Renault" }, 
   new SelectListItem { Value = "2", Text = "Peugeot" } 
};

Or Using a Datasource:

    VehicleMakeList = db.VehicleMakers /*EF, LINQ2SQL, ADO.NET or any supported external source*/
       .Select(v=> new SelectListItem { Text = v.Name, Value = v.Id})
       .ToList();

View:

@Html.DropDownListFor(model => model.VehicleMake, Model.VehicleMakeList)
JOBG
  • 4,544
  • 4
  • 26
  • 47
3

Binding dropdownlist is very tricky in MVC you can do it with this in your controller get all your cities list put it in viewBag

Create

      ViewBag.CityId = new SelectList(db.Cities, "ID", "Name");

user.CityID if you are in Edit so that on edit it select the city

      ViewBag.CityId = new SelectList(db.Cities, "ID", "Name", user.CityID);

in your View just do this trick

     @Html.DropDownList("CityId", "Select")

this is the most simplest way I know....

dnxit
  • 7,118
  • 2
  • 30
  • 34
  • Typically viewbag is not a recommended storage approach, especially for _model_ data. These should be encapsulated from the _model_ into the _viewmodel_. – RJ Kelly Feb 18 '18 at 05:05
  • The *point* to my comment, its cumbersome to separate the Dropdowns from the "model" presentation, this doesnt yield a good result long term.. Make a *ViewModel* and encapsulate the lists, then partial view updates for changes to "step by step" rules. Use the same rules on "Partials" to then refine the other select(s) you have in the partial. https://stackoverflow.com/questions/9517627/converting-html-editorfor-into-a-drop-down-html-dropdownfor – RJ Kelly Feb 18 '18 at 05:15
0

binding dropdown list is easy. code as follows

public ActionResult BindWithModel()
{
    List<SelectListItem> items = new List<SelectListItem>();

    items.Add(new SelectListItem 
                { Text = "Select Category", Value = "0", 
                        Selected = true });
    items.Add(new SelectListItem
                { Text = "Beverages", Value = "1" });
    items.Add(new SelectListItem
                { Text = "Condiments", Value = "2" });
    items.Add(new SelectListItem
                { Text = "Confections", Value = "3" });
    items.Add(new SelectListItem
                { Text = "Dairy Products", Value = "4" });
    items.Add(new SelectListItem
                { Text = "Grains/Cereals", Value = "5" });
    items.Add(new SelectListItem
                { Text = "Meat/Poultry", Value = "6" });
    items.Add(new SelectListItem
                { Text = "Produce", Value = "7" });
    items.Add(new SelectListItem
                { Text = "Seafood", Value = "8" });

    var model = new CategoryModel()
    {
        lstCategory = items,
        selected = 1
    };

    return View(model);
}

Code in view

@model BindMvcDropdownList.Models.CategoryModel

<h1>Bind MVC DropDownList with Model</h1>

@Html.DropDownListFor(x => x.selected, Model.lstCategory)

code taken from here http://dotnetmentors.com/mvc/how-to-bind-dropdownlist-in-asp-net-mvc-application.aspx

Mou
  • 15,673
  • 43
  • 156
  • 275