2011-01-21 128 views
6
    <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> 

我想在控制器中绑定此DropDownList。我的意思是我怎样才能得到控制器类中action方法中dropDownList的值。谢谢。Asp.Net MVC DropDownList数据绑定

回答

9

我看到您正在使用带有runat="server"asp:XXX网页控件的表单。这些概念不应该在ASP.NET MVC中使用。这些服务器控件所依赖的没有更多的ViewState和PostBacks。

所以在ASP.NET MVC你会通过定义表示数据视图模型开始:

public class ItemsViewModel 
{ 
    public string SelectedItemId { get; set; } 
    public IEnumerable<SelectListItem> Items { get; set; } 
} 

那么就需要定义有两个动作(一个呈现视图控制器和另一个手柄表单提交):

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 
     ... 
    } 
} 

最后你会写相应的强类型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> 

这是说,你也可以硬编码此选择您的视图中(虽然这是我不会推荐):

<% 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" /> 
<% } %> 

,并具有以下控制器:

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 
     ... 
    } 
} 
+0

哪有我使用这个代码var model = new ItemsViewModel { Items = new [] { new SelectListItem {Value =“Theory”,Text =“Theory”}, new Select ListItem {Value =“Appliance”,Text =“Appliance”}, new SelectListItem {Value =“Lab”,Text =“Lab”} } };如果我想从数据库中获取下拉列表的值。请给我建议我该怎么做,如果我从数据库中取值,那么我将使用哪些代码? – 2011-06-13 01:26:59

相关问题