View-to-Controller
Let us first discuss how to pass data from a ASP.NET MVC View to Controller. There are four ways to pass the data from View to Controller which are explained below:
- Traditional Approach: In this approach, we can use the request object of the
HttpRequestBase
class. This object contains the input field name and values as name-value pairs in case of the form submit. So we can easily get the values of the controls by their names using as indexer from the request object in the controller.For example: Let's say you are having an input in the form with name 'txtName
', then its values can be retrieved in controller from request object like below:Hide Copy Codestring strName = Request["txtName"].ToString();
- Through
FormCollection
: We can also get post requested data by theFormCollection
object. This object also has requested data as the name/value collection as theRequest
object.For example:Hide Copy Code[HttpPost] public ActionResult Calculate(FormCollection form) { string strName = form["txtName"].ToString(); . . . . . . . . . . . . . . . . . . . . }
- Through Parameters: We can also pass the input field names as parameters to the post action method by keeping the names same as the input field names. These parameters will have the values for those fields and the parameter types should be
string
. Also, there is no need to define the parameters in any specific sequence.For example:Hide Copy Code[HttpPost] public ActionResult Calculate(string txtName) { string strName = Convert.ToString(txtName); . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . }
In all of the above approaches, we need to even convert the non-string
type tostring
type due to which if any parsing fails, then the entire action may fail here. Here we have to convert each value to avoid any exceptions but, in the below 4th approach of passing data from view to controller, it reduces the amount of code. - Strongly typed model binding to view: Here, we need to create a strongly typed view which will bind directly the model data to the various fields of the page.For example:
- Create a model with the required member variables.Let's say we have a model named '
Person
' with member variable named as 'Name
' - Now pass the empty model to the view as parameter in the controller action.For example:Hide Copy Code
public ActionResult GetName() { Person person = new Person(); return View(person); }
- Prepare the strongly typed view to display the model property values through html elements as below:For example:Hide Copy Code
<div><%= Html.Encode(person.Name) %></div>
- Create the action method that handles the POST request & processes the data.For example:Hide Copy Code
[HttpPost] public ActionResult GetPersonName(Person person) { return Content(person.Name.ToString()); }
- Create a model with the required member variables.
Controller-to-View
There are three options to pass information from controller to view. They are mentioned below:
ViewData
: TheViewData
is aDictionary
of objects that are derived from the 'ViewDataDictionary
' class and its having keys asstring
type and a value for respective keys. It contains anull
value on each redirection and it needs typecasting for complex data types.For example: Assign value in controller action like:Hide Copy CodeViewData["PersonName"] = "Test Name";
Fetch thisViewData
value inView
like this:Hide Copy Code<h1><%= ViewData["PersonName"] %></h1>
ViewBag
:ViewBag
is just a dynamic wrapper aroundViewData
and exists only in ASP.NET MVC 3.ViewBag
is a dynamic property that takes advantage of the new dynamic features in C# 4.0. It doesn't require typecasting for complex data types. It also contains anull
value when redirection occurs.For example: Assign value in controller action like:Hide Copy CodeViewBag.PersonName= "Test Name";
Fetch thisViewData
value inView
like this:Hide Copy Code<h1><%= ViewBag.PersonName %></h1>
TempData
:TempData
by default uses the session to store data, so it is nearly same to session only, but it gets cleared out at the end of the next request. It should only be used when the data needs only to persist between two requests. If the data needs to persist longer than that, we should either repopulate theTempData
or use the Session directly.For example:Hide Copy CodeIn Controller : TempData["PersonName"] = "Test Name";
In View:Hide Copy Code<h1><%= TempData["PersonName"] %></h1>
Controller-to-Controller
If it's not private, just pass it as JSON object on the URL using the third parameter in the redirect as given in the below example:
Hide Copy Code
return RedirectToAction("ActionName", "ControllerName", new { userId = id });
If it is
private
data, we can use TempData
- which will be removed at the end of the request after the next request reads it.
No comments:
Post a Comment