@Html.EditorForModel() Dropdown

I am working on MVC4 , using @Html.EditorForModel() , it is showing dropdownlist as a text box, I want to show Dropdown list by setting any attribute and overriding template. Please share me MVC4 example for this.

@model Models.Employee

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Employee</legend>
        @Html.EditorForModel()
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Thanks in advance.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You could define a view model that will represent a dropdown:

public class ItemsViewModel
{
    public string SelectedValue { get; set; }

    public IEnumerable<SelectListItem> Values { get; set; }
}

which will be used in your main view model:

public class MyViewModel
{
    public ItemsViewModel DropDown1 { get; set; }
    public ItemsViewModel DropDown2 { get; set; }
    ...
}

Now all that’s left is write a custom editor template for the ItemsViewModel which should be placed in ~/Views/Shared/EditorTemplates/ItemsViewModel.cshtml. Notice that the name and location of the template is important:

@model ItemViewModel
@Html.DropDownListFor(x => x.SelectedValue, Model.Values)

and that’s pretty much all it takes.

Method 2

It’s the overriding template a requisite? You could use the @Html.DropDownList() helper.

There is a full example about how to use in the asp.net website and you can download the project: Here


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x