I am new to asp.net mvc. I have this controller that takes in a few parameters and then returns a view that gets data based on the input parameters.
I want to accept the input parameters as an object (for example instead of first name, last name and age, I want a person class that has these three parameters as its properties). Now my question is does the input parameter class (Person class) qualify to be called view model? If yes. Do I make the return view model a part of this class?
In other words which of the bottom two approaches is preferred
Case 1: Same class for input and return
public ActionResult GetPersonDetails(Person p)
{
return View(new Person {....})
}
Case 2: Separate classes for input and return
public ActionResult GetPersonDetails(Person p)
{
return View(new PersonDetails {....})
}
In MVC we cannot pass multiple models from a controller to the single view.
You can use multiple models in a single view by creating a common model for all the models that are to be used in a single view. To achieve this, refer to the following steps. First, create a new model (common for all models) and refer all other models that are to be used in the same view.
This blog will discuss four (4) common ways to pass data from the view to the controller: Passing by Typed Arguments. Request Object. Form Collections Object.
A controller action might return a view.
Now my question is does the input parameter class (Person class) qualify to be called view model?
Yes.
If yes. Do I make the return view model a part of this class?
Not necessarily. You could have different view model passed to the view as the one that your controller action is taking as parameter, although this is rare case scenario. It would really depend on your specific case but the general pattern is the following:
[HttpGet]
public ActionResult Index()
{
MyViewModel model = ...
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
// Some validation error occurred => redisplay the same view so
// that the user can fix his errors
return View(model);
}
// at this stage the view model has passed all validations =>
// here you could attempt to pass those values to your backend
// TODO: do something with the posted values like updating a database or something
// Finally redirect to a successful action Redirect-After-Post pattern
// http://en.wikipedia.org/wiki/Post/Redirect/Get
return RedirectToAction("Success");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With