Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC create using derived class

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");
}
like image 267
user1147941 Avatar asked Jan 21 '26 02:01

user1147941


1 Answers

Your best bet here is to have multiple POST actions in your controller.

So in the forms in your partial views, specify the action to hit

@using (Html.BeginForm("CreateStudent", "Create")) {

and

@using (Html.BeginForm("CreateProfessor", "Create")) {

Then your controller will look something like this:

[HttpPost]
public ActionResult CreateStudent(Student student)  
{
    //access the properties with the dot operator on the student object
    //process the data
    return RedirectToAction("Index");
}

and

 [HttpPost]
 public ActionResult CreateProfessor(Professor professor)  
 {
     //access the properties with the dot operator on the professor object
     //process the data
     return RedirectToAction("Index");
 }
like image 122
Forty-Two Avatar answered Jan 23 '26 20:01

Forty-Two