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 ?
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
user.CityID if you are in Edit so that on edit it select the city
in your View just do this trick
this is the most simplest way I know....
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:
I think the model for dropdownlist should be:
And initialized like:
Or Using a Datasource:
View:
binding dropdown list is easy. code as follows
Code in view
code taken from here http://dotnetmentors.com/mvc/how-to-bind-dropdownlist-in-asp-net-mvc-application.aspx