我通過viewbag獲取dropdownlist中的動態值,dropdownlist值顯示正確,但我的問題是張貼,我得到問題插入dropdownlist值在sql server中,請幫我解決這個問題。如何使用mvc 4將dropdownlist viewbag值發佈到sql server?
這是我的模型頁面,
public class RegisterModel
{
public Prefix Prefix { get; set; }
}
public class Prefix
{
public int? ID { get; set; }
public string Name { get; set; }
}
這是我的控制器頁,
void BindPrefix()
{
List<Prefix> lstPrefix = new List<Prefix>()
{
new Prefix { ID = null, Name = "Select" },
new Prefix { ID = 1, Name = "Mr" },
new Prefix { ID = 2, Name = "Ms" },
new Prefix { ID = 1, Name = "Mrs" },
new Prefix { ID = 2, Name = "Dr" }
};
ViewBag.Prefix = lstPrefix;
}
public ActionResult Register()
{
BindPrefix();
return View();
}
[HttpPost]
public ActionResult Register(FormCollection FC)
{
string Prefix =FC[ViewBag.Prefix]; // here prefix get null value.
return view();
}
這是我的看法頁,
@Html.DropDownListFor(m => m.Prefix.ID, new SelectList(ViewBag.Prefix, "ID", "Name", ViewBag.pef))
ViewBag信息對每個請求持續存在,這就是爲什麼您在發佈操作中ViewBag.Prefix等於null的原因。 – bsting 2014-11-21 07:45:55
您查看是基於模型'RegisterModel',所以回發模型'公衆ActionResult註冊(RegisterModel模型)'這將被正確綁定 – 2014-11-21 07:48:13
我使用ActionResult,但我也顯示null,因爲前綴是布爾數據類型 – 2014-11-21 09:03:11