2013-08-23 143 views
2

我想添加一个DropDownList到我的视图中,但没有使用ViewBag的静态选项,我希望它与模型绑定。我怎样才能做到这一点?Razor MVC中的下拉列表4

+3

你尝试过什么吗? –

+0

在您的浏览器中写入'' – Omu

回答

4

好,你开始写视图模型:

public class MyViewModel 
{ 
    public string SelectedValue { get; set; } 
    public IEnumerable<SelectListItem> Values { get; set; } 
} 

然后控制器操作将填充这个视图模型,并将其传递给视图:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     var model = new MyViewModel(); 

     // TODO: those values will probably be coming from a database or something 
     model.Values = new[] 
     { 
      new SelectListItem { Value = "1", Text = "item 1" }, 
      new SelectListItem { Value = "2", Text = "item 2" }, 
      new SelectListItem { Value = "3", Text = "item 3" }, 
     }; 

     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(MyViewModel model) 
    { 
     string selectedValue = model.SelectedValue; 
     return Content("You selected: " + selectedValue); 
    } 
} 

最后一个强类型您可以在其中使用Html.DropDownListFor帮手:

@model MyViewModel 

@using (Html.BeginForm()) 
{ 
    @Html.DropDownListFor(x => x.SelectedValue, Model.Values) 
    <button type="submit">OK</button> 
} 

帮手req uires 2参数:第一个参数是视图模型中标量属性的lambda表达式,它将保存选定的值,第二个参数只是一个IEnumerable<SelectListItem>属性,该属性包含将显示在下拉列表中的所有可用值。