我需要在表单中使用简单的DropDownList,我不想创建像ViewModel这样的东西。 我在关系1中有两个模型(表格):n:
public class Course
{
public int ID { get; set; }
public string Name { get; set; }
}
和
public class Project
{
public int ID { get; set; }
public int CourseId { get; set; }
public int ProjectNo { get; set; }
public string Name { get; set; }
public DateTime Deadline { get; set; }
}
在“创建项目”中,我希望从课程表(模型)中获取带有Id(作为值)和名称(作为文本)的DropDownList。在新项目中将插入选择的CourseId。我怎么能尽可能简单地做到这一点?
答案 0 :(得分:5)
您不想使用ViewModel的任何特殊原因?他们对这类问题非常有帮助。
如果您不想使用ViewModel,那么您可以在控制器中构造一个特定的类,它是两个类所需属性的集合:
public ActionResult Show(int id)
{
Course course = repository.GetCourse(id); // whatever your persistence logic is here
Project project = projectRepository.GetProjectByCourseId(id);
string CourseName = from c in course where
c.ID == project.courseID
select c.Name;
IEnumerable<SelectListItem> selectList =
from c in course
select new SelectListItem
{
Selected = (c.ID == project.CourseId),
Text = c.Name,
Value = project.CourseId.ToString()
};
//add the selectList to your model here.
return View(); //add the model to your view and return it.
}
为此设置ViewModel要容易得多,因此您可以拥有强类型视图。让我告诉你:
public class ProjectCourseViewModel
{
public SelectList ProjectCourseList {get; private set; }
public Project Project {get; private set; }
public Course Course {get; private set; }
public ProjectCourseViewModel(Project project, Course course)
{
ProjectCourseList = GetProjectCourseSelectList(project, course)
Project = project;
Course = course;
}
private SelectList GetProjectCourseSelectList(Project project, Course course)
{
IEnumerable<SelectListItem> selectList =
from c in course
select new SelectListItem
{
Selected = (c.ID == project.CourseId),
Text = c.Name,
Value = project.CourseId.ToString()
};
}
}
然后你的控制器会非常简单:
public ActionResult Show(int id)
{
Course course = repository.GetCourse(id);
Project project = projectRepository.GetProjectByCourseId(id);
ProjectCourseViewModel pcvm = new ProjectCourseViewModel(project, course)
return View(pcvm);
}
然后你的观点采用强类型模型,你不必依赖ViewData
,这是一件好事。
注意:我没有编译它,只是编写它。可能存在编译错误。
答案 1 :(得分:2)
可能您可以使用以下示例解决它:
控制器中的包含一个Viewbag
{
Viewbag.Course = db.course.ToList();
var project = new project.....
}
在您的视图中使用以下模式:
@Html.DropDownList("CourseId",
new SelectList(ViewBag.Course as System.Collections.IEnumerable,
"CourseId", "Name", Model.ID))
其中每个字段代表:
•表单字段的名称(CourseId)
•下拉列表的值列表,作为SelectList传递
•应使用表单
回发的“数据值”字段•数据文本字段,应显示在下拉列表中
•选择的值,用于在显示表单时设置下拉列表值
更多信息:http://www.asp.net/mvc/tutorials/mvc-music-store-part-5 brgds。
答案 2 :(得分:2)
在Controler中:
var CourseName = from c in course where
c.ID == project.courseID
select c.Name;
SelectList sl = new SelectList(CourseName);
ViewBag.names= sl;
视图中的:
@Html.DropDownList("Name", (SelectList)ViewBag.names)