以下はビューです:
<%@ 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 になるのはなぜですか?