3

I'm new to MVC, so I apologize in advance if something doesn't make sense.

I have a base class (let's say "Person"), and 2 derived classes ("Student", "Professor").

I want to use 1 view for the Create functionality, with Partial views that contain the creation forms for either a student or professor. If I add a parameter, I can check against that to determine which partial view to show.

But my question is this: When the "Create" button is clicked, how can I determine which object is being created?

Edit (please bear w/ me, as I just created these to illustrate the problem)

Person class:

public class Person
{
    public string Gender { get; set; }
    public int ID { get; set; }
}

Student class:

public class Student : Person
{
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public List<Course> Courses { get; set; }
}

Professor class:

public class Professor : Person
{
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public double AnnualSalary { get; set; }
}

So then my Create controller looks like this:

public ActionResult Create(int personType)    //1=student, 2=professor
{
    var x = new {
            Student = new Student(),
            Professor = new Professor()
        };
    ViewBag.PersonType = personType;
    return View(x);
}

Then my view looks like this:

<div>
@if (ViewBag.PersonType == 1)
{
    @Html.Partial("CreateStudentPartialView", Model.Student)
}
else 
{
    @Html.Partial("CreateProfessorPartialView", Model.Professor)
}

So, the question is what would the associated create action look like, when the "Create" button is clicked in either partial view?

[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");
}
4

1 に答える 1

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");
 }
于 2013-01-28T19:19:09.973 に答える