我看到您正在使用帶有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
...
}
}
哪有我使用這個代碼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