Click here to Skip to main content
15,867,568 members
Articles / Web Development / ASP.NET
Technical Blog

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

Rate me:
Please Sign up or sign in to vote.
4.78/5 (20 votes)
12 Apr 2014CPOL3 min read 392.1K   32   11
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 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.

    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:

    C#
    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.

    For example:

    C#
    [HttpPost]
    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, there is no need to define the parameters in any specific sequence.

    For example:

    C#
    [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 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 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:

    1. Create a model with the required member variables.

      Let's say we have a model named 'Person' with member variable named as 'Name'

    2. Now pass the empty model to the view as parameter in the controller action.

      For example:

      C#
      public ActionResult GetName()
      {
          Person person = new Person();
          return View(person);
      }
    3. Prepare the strongly typed view to display the model property values through html elements as below:

      For example:

      HTML
      <div><%= Html.Encode(person.Name) %></div>
    4. Create the action method that handles the POST request & processes the data.

      For example:

      C#
      [HttpPost]
      public ActionResult GetPersonName(Person person)
      {    
          return Content(person.Name.ToString());
      }

Controller-to-View

There are three options to pass information from controller to view. They 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.

    For example: Assign value in controller action like:

    C#
    ViewData["PersonName"] = "Test Name";

    Fetch this ViewData value in View like this:

    HTML
    <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.

    For example: Assign value in controller action like:

    C#
    ViewBag.PersonName= "Test Name";

    Fetch this ViewData value in View like this:

    HTML
    <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.

    For example:

    C#
    In Controller : TempData["PersonName"] = "Test Name";

    In View:

    HTML
    <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:

C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
Having more than 9 years of development experience in various Microsoft Technologies like :-
ASP.Net, MVC, SQL Server, WCF, MS Commerce Server, Xamarin etc.

Also hands on experience on the client side coding with JavaScript/jQuery and framework like AngularJS. Worked with third party ASP.net controls like Telerik and DevExpress as well.

Very much interested in Microsoft technologies to explore and implement. Now started to helping coders who really need me.

My Blog


Microsoft Technology Master

Programming Communities


JS Fiddle | Stack Overflow

Awards


Microsoft MCTS Certification in ASP.Net 4.0

Comments and Discussions

 
GeneralMy vote of 5 Pin
k.satyam0072-Jan-19 23:12
k.satyam0072-Jan-19 23:12 
GeneralGood info, straight to the point :-) Pin
aymkam26-Aug-15 3:43
aymkam26-Aug-15 3:43 
GeneralMy vote of 4 Pin
Gaurav Aroraa27-Oct-14 11:34
professionalGaurav Aroraa27-Oct-14 11:34 
QuestionCan we use ViewBag or ViewData to pass data from View to Controller? Pin
Pratik Gaikwad10-Jul-14 18:19
Pratik Gaikwad10-Jul-14 18:19 
Can I use the code as given below in the controller?

C#
if (ViewBag.PageCount != null)
                nPageCount = ViewBag.PageCount;

AnswerRe: Can we use ViewBag or ViewData to pass data from View to Controller? Pin
SRS(The Coder)10-Jul-14 19:17
professionalSRS(The Coder)10-Jul-14 19:17 
GeneralRe: Can we use ViewBag or ViewData to pass data from View to Controller? Pin
Pratik Gaikwad10-Jul-14 19:26
Pratik Gaikwad10-Jul-14 19:26 
GeneralRe: Can we use ViewBag or ViewData to pass data from View to Controller? Pin
SRS(The Coder)10-Jul-14 19:33
professionalSRS(The Coder)10-Jul-14 19:33 
GeneralRe: Can we use ViewBag or ViewData to pass data from View to Controller? Pin
Pratik Gaikwad11-Jul-14 7:50
Pratik Gaikwad11-Jul-14 7:50 
QuestionPassing multiple values from a view to a controller. Pin
Kwame Mensah Twum25-Jun-14 11:47
Kwame Mensah Twum25-Jun-14 11:47 
AnswerRe: Passing multiple values from a view to a controller. Pin
Pradeep_Kumar_Verma2-Jul-14 0:53
Pradeep_Kumar_Verma2-Jul-14 0:53 
AnswerRe: Passing multiple values from a view to a controller. Pin
Member 1124618918-Nov-14 23:13
Member 1124618918-Nov-14 23:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.