Jac*_*zek 3 asp.net asp.net-mvc-3
我需要在表单中使用简单的DropDownList,我不想创建像ViewModel这样的东西.我在关系1中有两个模型(表):n:
public class Course
{
public int ID { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
和
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; }
}
Run Code Online (Sandbox Code Playgroud)
在"创建项目"中,我想从课程表(模型)中获取带有Id(作为值)和名称(作为文本)的DropDownList.在新项目中将插入选择的CourseId.我怎么能这么简单呢?
您不想使用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.
}
Run Code Online (Sandbox Code Playgroud)
为此设置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()
};
}
}
Run Code Online (Sandbox Code Playgroud)
然后你的控制器会非常简单:
public ActionResult Show(int id)
{
Course course = repository.GetCourse(id);
Project project = projectRepository.GetProjectByCourseId(id);
ProjectCourseViewModel pcvm = new ProjectCourseViewModel(project, course)
return View(pcvm);
}
Run Code Online (Sandbox Code Playgroud)
然后你的视图采用强类型模型,你不必依赖ViewData
,这是一件好事.
注意:我没有编译它,只是编写它.可能存在编译错误.
归档时间: |
|
查看次数: |
19371 次 |
最近记录: |