【发布时间】:2015-01-19 07:18:35
【问题描述】:
我通过 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 信息在每个请求中都会持续存在,这就是为什么在 post 操作中 ViewBag.Prefix 等于 null 的原因。
-
你的视图是基于模型
RegisterModel所以发回模型public ActionResult Register(RegisterModel model)这将被正确绑定 -
我使用了 ActionResult 但我也显示为 null,因为 Prefix 是布尔数据类型
-
Prefix是 not 类型的boolean。它是一个包含属性int? ID和string Name的复杂类型,您应该将ViewBag属性更改为另一个名称,例如ViewBag.PrefixList = lstPrefix;并删除 SelectList 构造函数的第 4 个参数 -
并从
lstPrefix中删除第一项,改为使用@Html.DropDownListFor(m => m.Prefix.ID, new SelectList(ViewBag.PrefixList, "ID", "Name"), "Select")。为什么你的 ID 值不是唯一的(你有两个“1”和两个“2”)——你怎么知道选择了什么?以及为什么你仍然需要一个复杂的属性 - 只选择一个字符串(“先生”,女士“等)有什么问题
标签: asp.net-mvc-4