2011-01-21 124 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

相關問題