Bru*_*lla 6 asp.net-mvc-2 drop-down-menu
<form id="Form1" runat="server">
<asp:DropDownList ID="dvmDrmList" runat="server">
<asp:ListItem>Theory</asp:ListItem>
<asp:ListItem>Appliance</asp:ListItem>
<asp:ListItem>Lab</asp:ListItem>
</asp:DropDownList>
</form>
Run Code Online (Sandbox Code Playgroud)
我想在控制器中绑定此DropDownList.我的意思是如何在控制器类的action方法中获取dropDownList的值.谢谢.
我看到你正在使用表单runat="server"和asp:XXXweb控件.这些概念永远不应该在ASP.NET MVC中使用.这些服务器控件不再依赖于ViewState和PostBack.
因此,在ASP.NET MVC中,您将首先定义表示数据的视图模型:
public class ItemsViewModel
{
public string SelectedItemId { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
那么你将定义一个带有两个动作的控制器(一个呈现视图,另一个呈现表单提交):
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new ItemsViewModel
{
Items = new[]
{
new SelectListItem { Value = "Theory", Text = "Theory" },
new SelectListItem { Value = "Appliance", Text = "Appliance" },
new SelectListItem { Value = "Lab", Text = "Lab" }
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(ItemsViewModel model)
{
// this action will be invoked when the form is submitted and
// model.SelectedItemId will contain the selected value
...
}
}
Run Code Online (Sandbox Code Playgroud)
最后你会写出相应的强类型Index视图:
<%@ Page
Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<AppName.Models.ItemsViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm()) { %>
<%= Html.DropDownListFor(x => x.SelectedItemId, new SelectList(Model.Items, "Value", "Text")) %>
<input type="submit" value="OK" />
<% } %>
</asp:Content>
Run Code Online (Sandbox Code Playgroud)
这就是说你也可以在你的视图中硬编码这个选择(虽然这是我不推荐的):
<% using (Html.BeginForm()) { %>
<select name="selectedItem">
<option value="Theory">Theory</option>
<option value="Appliance">Appliance</option>
<option value="Lab">Lab</option>
</select>
<input type="submit" value="OK" />
<% } %>
Run Code Online (Sandbox Code Playgroud)
并拥有以下控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string selectedItem)
{
// this action will be invoked when the form is submitted and
// selectedItem will contain the selected value
...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8576 次 |
| 最近记录: |