Click here to Skip to main content
Click here to Skip to main content
Technical Blog

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

, 12 Apr 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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:

    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:

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

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

      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:

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

      For example:

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

    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.

    For example: 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.

    For example:

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

    In View:

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

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)

Share

About the Author

SRS(The Coder)
Software Developer
India India
Having more than 4 years of development experience in various Microsoft Technologies like :-
ASP.Net, VB.Net, MVC, SQL Server, WCF, MS Commerce Server, Xamarin etc.
 
Also hands on experience on the client side coding with JavaScript/jQuery.
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
Follow on   Google+   LinkedIn

Comments and Discussions

 
GeneralMy vote of 4 PinmemberGaurav.Kumar.Arora27-Oct-14 12:34 
QuestionCan we use ViewBag or ViewData to pass data from View to Controller? PinmemberPratik Gaikwad10-Jul-14 19:19 
AnswerRe: Can we use ViewBag or ViewData to pass data from View to Controller? PinmemberSRS(The Coder)10-Jul-14 20:17 
GeneralRe: Can we use ViewBag or ViewData to pass data from View to Controller? PinmemberPratik Gaikwad10-Jul-14 20:26 
GeneralRe: Can we use ViewBag or ViewData to pass data from View to Controller? [modified] PinmemberSRS(The Coder)10-Jul-14 20:33 
GeneralRe: Can we use ViewBag or ViewData to pass data from View to Controller? PinmemberPratik Gaikwad11-Jul-14 8:50 
QuestionPassing multiple values from a view to a controller. PinmemberKwame Mensah Twum25-Jun-14 12:47 
AnswerRe: Passing multiple values from a view to a controller. PinmemberPradeep_Kumar_Verma2-Jul-14 1:53 
AnswerRe: Passing multiple values from a view to a controller. PinmemberMember 1124618919-Nov-14 0:13 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141223.1 | Last Updated 12 Apr 2014
Article Copyright 2014 by SRS(The Coder)
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid