Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DropDownList in ASP.NET MVC 3

<div class="editor-label">
    @Html.LabelFor(model => model.Category)
</div>
<div class="editor-field">

    @Html.EditorFor(model => model.Category)
    @Html.ValidationMessageFor(model => model.Category)
</div>

This gives me a label and a text box. How can I get a drop down list with static select items in place of the text box. Please help. I am new to ASP.NET MVC. I need solution / advice in Razor syntax.

like image 297
ZVenue Avatar asked Jun 03 '11 20:06

ZVenue


People also ask

How bind dropdown from database in MVC?

For that add a View by right-clicking inside ActionResult and select AddView and provide its name as Index. After adding the View add a Namespace to the Model as shown below. Here we can directly access the MobileList from the Model. Now just run the application and just check it.


2 Answers

@Html.DropDownListFor( model => model.Category, new SelectList(new [] {"cat1", "cat2", "cat3"}) );
like image 110
Bala R Avatar answered Sep 28 '22 00:09

Bala R


Here is how you would populate a DropDownList using Model, View and Controller.

First the view

@using Website.Models
@model PageWithSelectList
@{
    ViewBag.Title = "Index";
}
@Html.DropDownList("DayOfWeek", Model.DaysOfWeek)

Then the Controller and Action method

using System.Web.Mvc;
using Website.Models;

namespace Website.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new PageWithSelectList();
            model.DayOfWeek = 3;
            return View(model);
        }
    }
}

and the HTML output

<select id="DayOfWeek" name="DayOfWeek">
<option value="1">Sunday</option>
<option value="2">Monday</option>
<option selected="selected" value="3">Tuesday</option>
<option value="4">Wednesday</option>
<option value="5">Thursday</option>
<option value="6">Friday</option>
<option value="7">Saturday</option>
</select>

I hope this helps.

like image 35
wayne.blackmon Avatar answered Sep 28 '22 01:09

wayne.blackmon