我是MVC的新手,所以如果事情没有意义,我会事先道歉。
我有一个基类(让我们说“人”)和2个派生类(“学生”,“教授”)。
我想在创建功能中使用1个视图,其中部分视图包含学生或教授的创建表单。如果我添加一个参数,我可以检查它以确定要显示的部分视图。
但我的问题是:点击“创建”按钮后,如何确定正在创建哪个对象?
修改(请与我联系,因为我刚刚创建了这些以说明问题)
人员类:
public class Person
{
public string Gender { get; set; }
public int ID { get; set; }
}
学生班:
public class Student : Person
{
public string LastName { get; set; }
public string FirstName { get; set; }
public List<Course> Courses { get; set; }
}
教授班:
public class Professor : Person
{
public string LastName { get; set; }
public string FirstName { get; set; }
public double AnnualSalary { get; set; }
}
那么我的Create控制器看起来像这样:
public ActionResult Create(int personType) //1=student, 2=professor
{
var x = new {
Student = new Student(),
Professor = new Professor()
};
ViewBag.PersonType = personType;
return View(x);
}
然后我的观点如下:
<div>
@if (ViewBag.PersonType == 1)
{
@Html.Partial("CreateStudentPartialView", Model.Student)
}
else
{
@Html.Partial("CreateProfessorPartialView", Model.Professor)
}
所以,问题是当在任一局部视图中点击“创建”按钮时,相关的创建动作会是什么样的?
[HttpPost()]
public ActionResult Create(....) //What would I put as parameter(s)?
{
//no idea what to do here, since I don't know what object is being passed in
return RedirectToAction("Index");
}
答案 0 :(得分:2)
这里最好的选择是在你的控制器中有多个POST动作。
因此,在部分视图的表单中,指定要执行的操作
@using (Html.BeginForm("CreateStudent", "Create")) {
和
@using (Html.BeginForm("CreateProfessor", "Create")) {
然后你的控制器看起来像这样:
[HttpPost]
public ActionResult CreateStudent(Student student)
{
//access the properties with the dot operator on the student object
//process the data
return RedirectToAction("Index");
}
和
[HttpPost]
public ActionResult CreateProfessor(Professor professor)
{
//access the properties with the dot operator on the professor object
//process the data
return RedirectToAction("Index");
}