Wednesday, October 23, 2013

Passing Data [View-to-Controller, Controller-to-View & Controller-to-Controller in ASP.Net MVC]

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 being explained below :-

1) 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.
Ex :-
        Let say you are having a input in the form with name 'txtName' then its values can be retrieved in controller from request object like as below :
                     string strName = Request["txtName"].ToString();

2) Through FormCollection: We can also get post requested data by the FormCollection object. This object also has requested data as the name/value collection as the Request object. 
Ex :             
public ActionResult Calculate(FormCollection form) 
        string strName = form["txtName"].ToString();
        . . . . . . . . . . . . . . . . . . . . 

3) 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 no need to define the parameters in any specific sequence.

Ex : 
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 to string 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.

4) Strongly type 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.

Ex :- 
i) Create a model with the required member variables.
Let say we have a model named 'Person' with member variable named as 'Name'
ii) Now pass the empty model to teh view as parameter in the controller action.
Ex : 
public ActionResult GetName()
    Person person = new Person();
    return View(person);
iii) Prepare the strongly typed view to display the model property values through html elements as below :-
Ex -
         <div><%= Html.Encode(person.Name) %></div>

iv) Create the action method that handles the POST request & processes the data.
Ex : 
public ActionResult GetPersonName(Person person)
    return Content(person.Name.ToString());


           There are three options to pass information from controller to view. Here are mentioned below :-
1) ViewData: The ViewData is a Dictionary of objects that are derived from the 'ViewDataDictionary' class and its having keys as string type and a value for respective keys. It contains a null value on each redirection and it needs typecasting for complex data types.
Ex :- Assign value in controller action like :
ViewData["PersonName"] = "Test Name";
Fetch this ViewData value in View like this - <h1><%= ViewData["PersonName"]  %></h1>

2) ViewBag: ViewBag is just a dynamic wrapper around ViewData 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 a null value when redirection occurs.
Ex :- Assign value in controller action like :
ViewBag.PersonName= "Test Name";
Fetch this ViewData value in View like this - <h1><%= ViewBag.PersonName  %></h1>

3) 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 the TempData or use the Session directly.
Ex :-
In Controller : TempData["PersonName"] = "Test Name";
In View :  <h1><%= TempData["PersonName"]  %></h1>


If its not private, just pass it as JSON object on the url using the third parameter in the redirect like below example :

               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.


  1. Do you know how does the model gets filled on post back of the form.

    After the page rendering the page is nothing but a plain html , if used the widgets for the form creation then it will have the id name as that of the model property name. Then at the time of the post back all the form data will be posted back to the server and it now the job of the aspnet engine to wire back to the model just by mapping the DOM id with that of the model property.