Creating MVC Using Derived Class
I'm new to MVC, so apologize in advance if something doesn't make sense.
I have a base class (say "Face") and 2 derived classes ("Student", "Professor").
I want to use 1 view for the Create function, with partial views that contain creation forms for a student or professor. If I add a parameter, I can test it 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 feel free, I just created these to illustrate the problem)
Character 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's class:
public class Professor : Person
{
public string LastName { get; set; }
public string FirstName { get; set; }
public double AnnualSalary { get; set; }
}
So 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 will the associated create action look like when the Create button is clicked, either in a 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");
}
source to share
Your best bet here is to have multiple POST actions in your controller.
So, in the forms of your partial views, specify the action to be clicked
@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");
}
source to share