Default value for Drop down in Razor view RRS feed

  • Question

  • User-1331543185 posted

    I have a drop down in razor view that gets its value from Dictionary in C# code: Dictionary of bed is

     1   Studio
     2   1+
     3   2+

    and this is drop down is view:

        <select id="bedroom" name="bedroom" class="form-control">
            {{#each bed}}
              <option value="{{id}}" {{#if 

    How I can make the 1+ selected as default, now the Studio is default as it is Db is returning. Now it shows Studio as Default. 

    Friday, May 17, 2019 7:35 PM

All replies

  • User-1174608757 posted

    Hi nokot

    According to your code.It doesn't seem be a pure razor grammar.So could you please tell me that have you used any library or tool for creating  dropdown in Razor view?

    Then, in razor page, when we create a dropdown, if we want set the default value, we always put the index and value in a model and put the list in the ViewBag,then we could call the model in View.Here is a demo, I hope it could help you.


    namespace mvctest.Controllers
        public class Model
            public int Id { get; set; }
            public string Value { get; set; }
        public class HomeController : Controller
            public ActionResult Index()
                ArrayList list = new ArrayList();
                list.Add(new { id = 1, value = "studio" });
                list.Add(new { id = 2, value = "1+" });
                list.Add(new { id = 3, value = "2+" });
                SelectList list1 = new SelectList(list, "id", "value");
                Model model = new Model
                    Id = 2,
                    Value = "1+"
                ViewBag.list = list1;
                return View(model);


        ViewBag.Title = "Home Page";
    @model    mvctest.Controllers.Model
    @Html.DropDownListFor(m => Model.Id, (SelectList)ViewBag.list)

    You could see:

    Best Regards


    Monday, May 20, 2019 2:56 AM