在我的MVC项目中,我有Course
模型,如下所示:
public class Course
{
[Key]
public int CourseId { get; set; }
[Required, MaxLength(50)]
public string Name { get; set; }
// bunch of other properties
}
我正在为我的Action
中的某些Courses
创建一个SelectList
var user = context.Users.Include("Courses")
.FirstOrDefault(x => x.Email == User.Identity.Name);
var courses = user.Courses.OrderBy(x => x.Name);
ViewBag.Courses = new SelectList(courses, "CourseId", "Name");`
我的courseId
中有一个可以为Action
的可参数,如下所示:
public ActionResult Index(int? courseId)
如果它不为null,我想将默认选择的值更改为该课程。为此,我尝试了:
if (courseId != null)
{
var selectedCourse = courses
.FirstOrDefault(x => x.CourseId == courseId.Value);
if (selectedCourse != null)
{
ViewBag.Courses = new SelectList(courses, "CourseId", "Name", selectedCourse.CourseId);
}
}
但它不起作用且selectedCourse
不 null
。而不是指定Course
我每次都会看到列表中的第一个课程。我错过了什么?
编辑:我正在DropdownList
创建View
,如下所示:
@Html.Bootstrap().DropDownList("Courses", (SelectList)ViewBag.Courses)
答案 0 :(得分:1)
您应该通过您的型号发送所选值,但是,如果您想通过viewbag发送,请尝试这样:
@Html.DropDownListFor(model => Model.CourseId,
new SelectList(ViewBag.Courses, "Value", "Text", @ViewBag.CourseId))
请在此处查看我对类似问题的原始回答,了解更多信息https://stackoverflow.com/a/16799915/1477388
答案 1 :(得分:1)
如果有任何答案可以解决您的问题。试试吧
将您选择的值放入ViewBag.Seleted
$("#DropDownId option").each(function(){
if($(this).val() == "ViewBag.Selected"){
$(this).attr("selected","selected");
}
});