MVC Dropdownlistfor<>

44,691

Solution 1

The values for the dropdownlist should be in your existing view model:

public class WhateverViewModel
{
    // All of your current viewmodel fields here
    public string SelectedCity { get; set; }
    public Dictionary<string, string> CityOptions { get; set; }
}

Populate these in your controller with whatever values you want (where SelectedCity is your numerical ID), then do the following in your view:

@Html.DropDownListFor(m => m.SelectedCity,
    new SelectList(Model.CityOptions, "Key", "Value", Model.SelectedCity))

If your values never change, you could hardcode them as a static member of your view model and then do:

@Html.DropDownListFor(m => m.SelectedCity,
    new SelectList(WhateverViewModel.CityOptions, "Key", "Value", Model.SelectedCity))

Either way, this is data for this view, so it belongs in your view model. If you're not using view models and this view is directly tied to a domain entity; you should be using them and now is as good a time as any to start.

Solution 2

You can also follow another approach which is to collect all dropdown lists in 1 helper class and return theses lists each with a static function.

Ex. Dropdown helper class

namespace Asko.Web.Mvc.Infrastructure.Utils
{
    public static class DropdownHelper
    {
        public static IEnumerable<SelectListItem> GetAllCategories()
        {
            var categories = category.GetAll();
            return categories.Select(x => new SelectListItem { Text = x.categoryName, Value = x.categoryId.ToString()}));
        }
    }
}

And here you are going to use it in the page:

<td style="width: 150px;">
      <b>Category: </b>
      <br>
 @Html.DropDownListFor(m => m.CategoryId, DropdownHelper.GetAllCategories())
</td>

Solution 3

If you want to avoid the usage of model, you may simply use a ViewBag. in your action:

ViewBag.DirectorId = new SelectList(ListOfItemsToAdd, "dataValueField", "dataTextField", movie.DirectorId);

and in the view:

<%= Html.DropDownList("VariableNameToPost", ViewBag.DirectorId) //for asp.net view engine %> 
@Html.DropDownList("VariableNameToPost", ViewBag.DirectorId) // for razor view engine

and the action that would accept the variable would then have something like this:

public ActionResult theAction(string VariableNameToPost){...}

refferences:

Solution 4

If you want to create a drop down directly on view regardless of controller and model then you can create it using following code

@Html.DropDownList("Departments", 
  new SelectList(new [] { new KeyValuePair<string, int>( "IT", 0 ), new KeyValuePair<string, int>( "HR", 1 )},"Value", "Key")) 
Share:
44,691
Shahnawaz
Author by

Shahnawaz

Hi All, I am here to reply the Question... I am not expert at all but try to learn from your question. I have enthusiasm to Answer you. Kindly remark my Answer how it is helpful for you. I enjoy to help the people. My hobbies is to read, reply and playing cricket. If it falls on your lot to be a street sweeper, sweep streets like Michelangelo painted pictures, like Shakespeare wrote poetry, like Beethoven composed music; sweep streets so well that all the host of Heaven and Earth will have to pause and say,"Here lived a great sweeper, who swept his job well. Enthusiasm is the yeast that makes your hopes rise to the stars. Enthusiasm is the sparkle in your eyes, the swing in your gait, the grip of your hand, the irresistible surge of will and energy to execute your ideas. Men are failures not because they are stupid, but because they are not sufficiently impassioned. Thanking you -- regards Helping for no Benefit.

Updated on March 11, 2020

Comments

  • Shahnawaz
    Shahnawaz about 4 years

    I just started a project in MVC. I am new to MVC asp.net. I want to add a dropdown list box like I used to add in asp.net.

    code glimpses in asp.net for Dropdownlist box

    <asp:Dropdownlist ID="ddlCity" runat="server">
    <asp:ItemList Text="Kolkatta" Value="1"/>
    <asp:ItemList Text="New Delhi" Value="2"/>
    <asp:ItemList Text="Mumbai" Value="3"/>
    <asp:ItemList Text="chennai" Value="4"/>
    <asp:ItemList Text="Hydrabad" Value="5"/>
    </asp:Dropdownlist>
    

    I want a dropdown list box in that manner.... meaning, now I need to create a model and controller for that. Suppose I have already have a view named "Employee Entry Form" and I need to add one dropdown list only on that page. I do not want to create a model for this dropdown list; I only need it on this page.

  • Shahnawaz
    Shahnawaz almost 11 years
    Thank you very much... for your instant reply. i solved it my self. i found that you added answer here which is copy paste.
  • Shahnawaz
    Shahnawaz almost 11 years
    It is ok for your time and answer... but i did my self and it is more easy and accurate than you...
  • Igarioshka
    Igarioshka almost 11 years
    @Shahnawaz could you post the solution and mark it as an answer so that other developers, that are having similar issues, could find it?
  • Shane Kenyon
    Shane Kenyon over 10 years
    There are definitely cases where, for performance reasons, you may want to create a specialized model for a given drop down. This would be tied to an actual database view designed to return only those specific key/value pairs needed for the drop down, and in most cases, the other keys used to pre-filter the drop down list. Ant, I realize your view model design allows for this, but I thought it helpful to explicitly call it out based on the original question.
  • T-student
    T-student about 8 years
    DropDownHelper dose not exist in current context why ?
  • qbik
    qbik about 6 years
    I would rather avoid Invoking a method that causes Database round-trip from a view. View should have everything ready in the Model, and data retrieval should be managed by Controller.