Reputation: 5027
<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.
Upvotes: 6
Views: 2444
Reputation: 11755
You can use the foolowing code
Controler
var list = new SelectList(new[]
{
new {ID="1",Name="Employee"},
new{ID="2",Name="Debtor"},
new{ID="3",Name="Supplier"},
new{ID="4",Name="Patient"},
},
"ID", "Name", 1);
ViewData["list"] = list;
return View();
View
<div class="editor-field">
@Html.DropDownListFor(model => model.type,ViewData["list"] as SelectList,
new { style = "width: 100px;"})
</div>
Upvotes: 0
Reputation: 749
Another way to fill your dropdownlist is by using the viewbag.
Controller:
public Action Create()
{
FillViewBag();
Return View();
}
private void FillViewBag()
{
List<SelectListItem> selectOptions = new List<SelectListItem>();
for(int i = 1; i <= 3; i++)
{
SelectListItem sli = new SelectListItem();
sli.Text = "Option " + i.ToString();
sli.Value = i.ToString();
selectOptions.Add(sli)
}
ViewBag.SelectOptions = selectOptions;
}
In your View:
@Html.DropDownListFor(model => model.yourProp, ViewBag.SelectOptions as IEnumerable<SelectListItem>)
Hope this helps you!
Upvotes: 0
Reputation: 761
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.
Upvotes: 3
Reputation: 108937
@Html.DropDownListFor( model => model.Category, new SelectList(new [] {"cat1", "cat2", "cat3"}) );
Upvotes: 10