下面是视图:
<%@ Page Title="" Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.Index>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Contact
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm())
{%>
<%=Html.DropDownListFor(x => x.SelectedFavColor, Model.DropDownItems)%>
<%= Html.ValidationMessageFor(x=> x.SelectedFavColor) %>
<input type="submit" value="submit" />
<%} %>
</asp:Content>
下面提到的是模型:
namespace MvcApplication1.Models
{
public class Index
{
[Range(0, 1000, ErrorMessage = "hello")]
public int SelectedFavColor { get; set; }
public IEnumerable<SelectListItem> DropDownItems { get; set; }
}
public class Colors
{
public int ColorID { get; set; }
public string ColorName { get; set; }
}
}
我在视图中传递了一些下拉值。下面是控制器动作:
public ActionResult Contact()
{
List<MvcApplication1.Models.Colors> l = new List<Models.Colors>();
l.Add(new Models.Colors { ColorName = "-1", ColorID = -1 });
l.Add(new Models.Colors { ColorName = "a", ColorID = 0 });
l.Add(new Models.Colors { ColorName = "b", ColorID = 2 });
l.Add(new Models.Colors { ColorName = "c", ColorID = 3 });
l.Add(new Models.Colors { ColorName = "d", ColorID = 4 });
l.Add(new Models.Colors { ColorName = "e", ColorID = 4 });
l.Add(new Models.Colors { ColorName = "f", ColorID = 4 });
var model = new MvcApplication1.Models.Index
{
DropDownItems = l.Select(i => new SelectListItem
{
Text = i.ColorName,
Value = i.ColorID.ToString()
})
};
ViewData["records"] = model.DropDownItems;
return View(model);
}
[HttpPost]
public ActionResult Contact(Index posted, FormCollection collection)
{
posted.SelectedFavColor = Convert.ToInt16(collection["SelectedFavColor"]);
return View(posted);
}
为什么 POST 操作中的 DropDown 值为 Null?