[英]Bind Dropdown using mvc4
我需要帮助来绑定模型中的下拉值。
Model.cs
public class BloodGroup
{
public BloodGroup()
{
ActionsList = new List<SelectListItem>();
}
[Display(Name="Blood Group")]
public int Group { get; set; }
public IEnumerable<SelectListItem> ActionsList { get; set; }
}
public class ActionType
{
public int GroupId { get; set; }
public string BloodGroup { get; set; }
}
在控制器中:
List<ActionType> actionType = GetCourses();
bGroup.ActionsList = from action in actionType
select new SelectListItem
{
Text = action.BloodGroup,
Value = ((int)action.GroupId).ToString(),
Selected = action.BloodGroup.Equals("A+")?true:false
};
return view;
public List<ActionType> GetCourses()
{
return new List<ActionType> {
new ActionType () { GroupId = 1, BloodGroup = "A+"},
new ActionType () { GroupId = 2, BloodGroup = "B+"},
new ActionType () { GroupId = 3, BloodGroup = "O+" },
new ActionType () { GroupId = 4, BloodGroup = "AB+" },
new ActionType () { GroupId = 5, BloodGroup = "A-"},
new ActionType () { GroupId = 6, BloodGroup = "B-"},
new ActionType () { GroupId = 7, BloodGroup = "O-" },
new ActionType () { GroupId = 8, BloodGroup = "AB-" }
};
}
它成功返回查看。 但鉴于绑定下拉列表会引发错误。
鉴于
@model MyMVC.Models.BloodGroup
@Html.DropDownListFor(m => m.Group, new SelectList(Model.ActionsList, "Value", "Text",true), "-- Select --")</li>
返回错误。
你调用的对象是空的。
Model .ActionsList设置为Null。
我不知道为什么它显示null,尽管我继承了模型。
我需要有关如何将SelectList值绑定到下拉列表的帮助
您需要在操作方法BloodGroup
类的实例传递给视图,如下所示:
public ActionResult YourAction()
{
List<ActionType> actionType = GetCourses();
var model = new BloodGroup()
{
ActionsList = (from action in actionType
select new SelectListItem
{
Text = action.BloodGroup,
Value = ((int) action.GroupId).ToString(),
Selected = action.BloodGroup.Equals("A+")
})
};
return View(model);
}
然后在您看来:
@model BloodGroup
@Html.DropDownListFor(m => m.Group, Model.ActionsList,"-- Select --")
注意
使用上面的例子,它会告诉你没有错误的观点,但在你所选择的项目downdownList
将无法正确显示。 为了正确显示所选项目,您需要将Grop
属性的类型更改为String
,如下所示:
public class BloodGroup
{
//
[Display(Name = "Blood Group")]
public string Group { get; set; }
//
}
然后使用上述相同的动作方法,使您的视图像:
@model BloodGroup
@Html.DropDownList("Group", Model.ActionsList, "-- Select --")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.