Click here to Skip to main content
11,715,165 members (63,785 online)
Click here to Skip to main content

Tagged as

Getting Data From View to Controller in MVC

, 30 Aug 2014 CPOL 173K 50
Rate this:
Please Sign up or sign in to vote.
This article explains how to access data from a view to the controller's action method.

Introduction

This article explains how to access data from a view to the controller's action method. The action method is a simple C# method that can be parameterized or without a parameter in the controller.

We use two types of methods to handle our browser request; one is HTTP GET and another is HTTP POST. When we call an action method by a request's URL by the browser then the HTTP GET method will be called but when a request is from a button click event then the HTTP POST method will be called. So in this article I am going to explaining how to access view input field data in the controller's action method when a HTTP POST request is called.

Example for GET and POST Request Type

To understand how to access view input field data in the controller's action method (POST), we create a "Calculate Simple Interest" application. This application gets Principle, Rate and Time as user input and generates simple interest. So let's proceed with the application.

Create an action method in the CalculateSimpleInterest controller (CalculateSimpleInterestController.cs) that renders the view on the UI.

public ActionResult SimpleInterest()
{
    return View();
}

Create a view to get user input from the UI, so the code is:

Calculate Simple Interest

<fieldset>
        <legend>Calculate Simple Interest</legend>
    @using (Ajax.BeginForm("CalculateSimpleInterestResult","CalculateSimpleInterest",
                            new AjaxOptions { UpdateTargetId = "divInterestDeatils" }))
    {
        <div id="divInterestDeatils"></div>
        <ol>
            <li>
                @Html.Label("Amount")
                @Html.TextBox("txtAmount")
            </li>
            <li>
                @Html.Label("Rate")
                @Html.TextBox("txtRate")
            </li>
            <li>
                @Html.Label("Year")
                @Html.TextBox("txtYear")
            </li>
        </ol>
    <button>Calculate</button>
    }   
</fieldset>

So now the screen is ready to get input and it shows it as:

UI input screen

Figure 1.1 Input screens to calculate simple interest

Get the view's data in the Action Method

I will now explain the four ways to get the view's data in the controller action. These are:

  • Using Traditional approach
  • Using the FormCollection Object
  • Using the Parameters
  • Strongly type model binding to view

Using Traditional Approach

In the traditional approach we use the request object of the HttpRequestBase class. The request object has view input field values in name/value pairs. When we create a submit button then the request type POST is created and calls the POST method.

UI input screen

Figure 1.2 Requested Data

We have four data, those are in Name-Value pairs. So we can access these data in a POST method by passing the Name as an indexer in the Request and get values. Our POST method means the controller action that handles the POST request type is:

[HttpPost]
public ActionResult CalculateSimpleInterestResult()
{
    decimal principle = Convert.ToDecimal(Request["txtAmount"].ToString());
    decimal rate = Convert.ToDecimal(Request["txtRate"].ToString());
    int time = Convert.ToInt32(Request["txtYear"].ToString());

    decimal simpleInteresrt = (principle*time*rate)/100;

    StringBuilder sbInterest = new StringBuilder();
    sbInterest.Append("<b>Amount :</b> " + principle+"<br/>");
    sbInterest.Append("<b>Rate :</b> " + rate + "<br/>");
    sbInterest.Append("<b>Time(year) :</b> " + time + "<br/>");
    sbInterest.Append("<b>Interest :</b> " + simpleInteresrt);
    return Content(sbInterest.ToString());
}

When it executes, we get simple interest as the result as in the following:

UI input screen

Figure 1.3 Output screen after getting response

Using the FormCollection Object

We can also get post requested data by the FormCollection object. The FormCollection object also has requested data in the name/value collection as the Request object. To get data from the FormCollection object we need to pass it is as a parameter and it has all the input field data submitted on the form.

[HttpPost]
public ActionResult CalculateSimpleInterestResult(FormCollection form)
{
    decimal principle = Convert.ToDecimal(form["txtAmount"].ToString());
    decimal rate = Convert.ToDecimal(form["txtRate"].ToString());
    int time = Convert.ToInt32(form["txtYear"].ToString());

    decimal simpleInteresrt = (principle*time*rate)/100;

    StringBuilder sbInterest = new StringBuilder();
    sbInterest.Append("<b>Amount :</b> " + principle+"<br/>");
    sbInterest.Append("<b>Rate :</b> " + rate + "<br/>");
    sbInterest.Append("<b>Time(year) :</b> " + time + "<br/>");
    sbInterest.Append("<b>Interest :</b> " + simpleInteresrt);
    return Content(sbInterest.ToString());
}

It also gives the same output as Figure 1.3 shows.

Using the Parameters

We can pass all input field names as a parameter to the post action method. The input field name and parameter name should be the same. These parameters have input field values that were entered by the user. So we can access view input field values from these parameters. The input field takes a string value from the user so the parameter should be a string type. There is no need to define a parameter in any specific sequence.

[HttpPost]
public ActionResult CalculateSimpleInterestResult(string txtAmount, string txtRate, string txtYear)
{
    decimal principle = Convert.ToDecimal(txtAmount);
    decimal rate = Convert.ToDecimal(txtRate);
    int time = Convert.ToInt32(txtYear);

    decimal simpleInteresrt = (principle*time*rate)/100;

    StringBuilder sbInterest = new StringBuilder();
    sbInterest.Append("<b>Amount :</b> " + principle+"<br/>");
    sbInterest.Append("<b>Rate :</b> " + rate + "<br/>");
    sbInterest.Append("<b>Time(year) :</b> " + time + "<br/>");
    sbInterest.Append("<b>Interest :</b> " + simpleInteresrt);
    return Content(sbInterest.ToString());
}

It also gives the same output as Figure 1.3 shows.

In all three approaches above we are parsing the string to a non-string type. If any of the parsing attempts fail then the entire action will fail. We are converting each value to avoid an exception but it also increases the amount of code. So we look at the fourth approach that would reduce the amount of code.

Strongly type model binding to view

We bind a model to the view; that is called strongly type model binding.

Step 1: Create a Model for Simple Interest.

namespace CalculateSimpleInterest.Models
{
    public class SimpleInterestModel
    {
        public decimal Amount { get; set; }
        public decimal Rate { get; set; }
        public int Year { get; set; }
    }
}

Step 2: Create an action method that render a view on the UI.

We are passing an empty model to be bound to the view.

public ActionResult SimpleInterest()
{
    SimpleInterestModel model = new SimpleInterestModel();
    return View(model);
}

Step 3: Create a strongly typed view that has the same screen as in Figure 1.1.

@model CalculateSimpleInterest.Models.SimpleInterestModel

@{
    ViewBag.Title = "SimpleInterest";
}
<h2>Calulate Simple Interest</h2>@using (Ajax.BeginForm("CalculateSimpleInterestResult","CalculateSimpleInterest",
                            new AjaxOptions { UpdateTargetId = "divInterestDeatils" }))
    {
       
    <fieldset>
        <legend>Calulate Simple Interest</legend><div id="div1"></div>
 
        <div class="editor-label">
            @Html.LabelFor(model => model.Amount)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Amount)          
        </div>
 
        <div class="editor-label">
            @Html.LabelFor(model => model.Rate)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Rate)          
        </div>
 
        <div class="editor-label">
            @Html.LabelFor(model => model.Year)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Year)           
        </div>
        <p>
            <input type="submit" value="Calculate" />
        </p>
    </fieldset>
 }
 
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Step 4: Create an action method that handles the POST request and processes the data.

In the action method we pass a model as the parameter. That model has UI input field data. Here we do not need to parse and do not need to write extra code.

[HttpPost]
public ActionResult CalculateSimpleInterestResult(SimpleInterestModel model)
{
    decimal simpleInteresrt = (model.Amount*model.Year*model.Rate)/100;
    StringBuilder sbInterest = new StringBuilder();
    sbInterest.Append("<b>Amount :</b> " + model.Amount+"<br/>");
    sbInterest.Append("<b>Rate :</b> " + model.Rate + "<br/>");
    sbInterest.Append("<b>Time(year) :</b> " + model.Year + "<br/>");
    sbInterest.Append("<b>Interest :</b> " + simpleInteresrt);
    return Content(sbInterest.ToString());
}

It also gives the same output as Figure 1.3 shows.

Conclusion

This article introduced that how can pass view data to controller action method. If you have any concerns, post as a comment or directly connect by https://twitter.com/ss_shekhawat.

License

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

Share

About the Author

Sandeep Singh Shekhawat
Software Developer
India India
Sandeep Singh Shekhawat is a Software Developer. He is awarded for C# Corner MVP(2013,2014 and 2015) and CodeProject MVP (2015). His three articles at CodeProject are prize wining in article competition. His more than 10 articles has been selected Article of the Day at Microsoft ASP.NET (http://www.asp.net/) community.

You may also be interested in...

Comments and Discussions

 
QuestionNeed help Pin
Co. Aden21-Jul-15 17:16
memberCo. Aden21-Jul-15 17:16 
QuestionThis code not work in MVC3 ? Pin
Dharmesh .S. Patil20-Jul-15 2:44
professionalDharmesh .S. Patil20-Jul-15 2:44 
Suggestionnot much helpful Pin
ajisactive23-Jun-15 19:38
memberajisactive23-Jun-15 19:38 
GeneralMy vote of 5 Pin
Tridip Bhattacharjee22-Mar-15 21:25
memberTridip Bhattacharjee22-Mar-15 21:25 
QuestionOne request regarding code Pin
Tridip Bhattacharjee22-Mar-15 21:24
memberTridip Bhattacharjee22-Mar-15 21:24 
QuestionPerfect solution Pin
Member 1108311321-Mar-15 2:56
memberMember 1108311321-Mar-15 2:56 
QuestionPOST method opens CalculateSimpleInterestResult in new page. Pin
joseph.scott.garza20-Feb-15 5:42
memberjoseph.scott.garza20-Feb-15 5:42 
AnswerRe: POST method opens CalculateSimpleInterestResult in new page. Pin
rishimuni16-Aug-15 21:37
memberrishimuni16-Aug-15 21:37 
GeneralMy vote of 1 Pin
Shiva Rudra29-Jan-15 0:27
memberShiva Rudra29-Jan-15 0:27 
QuestionNeat and Clean. Pin
Er. Puneet Goel21-Jan-15 19:04
professionalEr. Puneet Goel21-Jan-15 19:04 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun19-Jan-15 19:40
memberHumayun Kabir Mamun19-Jan-15 19:40 
QuestionThanks Pin
Nicolas Mertens24-Oct-14 1:08
memberNicolas Mertens24-Oct-14 1:08 
AnswerRe: Thanks Pin
Sandeep Singh Shekhawat9-Dec-14 0:39
professionalSandeep Singh Shekhawat9-Dec-14 0:39 
Questionhow do i add this to an edit controller so that it executes the button but stays in the edit view? Pin
icebox1251-Oct-14 7:56
membericebox1251-Oct-14 7:56 
GeneralMy vote of 5 Pin
Mahsa Hassankashi11-Sep-14 12:44
memberMahsa Hassankashi11-Sep-14 12:44 
GeneralRe: My vote of 5 Pin
Sandeep Singh Shekhawat11-Sep-14 15:14
professionalSandeep Singh Shekhawat11-Sep-14 15:14 
GeneralMy vote of 5 Pin
Kundan Singh Chouhan31-Aug-14 5:46
memberKundan Singh Chouhan31-Aug-14 5:46 
GeneralRe: My vote of 5 Pin
Sandeep Singh Shekhawat31-Aug-14 6:41
professionalSandeep Singh Shekhawat31-Aug-14 6:41 
QuestionThank you so much! Pin
Orit Ne21-Aug-14 5:39
memberOrit Ne21-Aug-14 5:39 
AnswerRe: Thank you so much! Pin
Sandeep Singh Shekhawat21-Aug-14 18:09
professionalSandeep Singh Shekhawat21-Aug-14 18:09 
Questionis it possible...? Pin
t4nu19-Aug-14 7:08
membert4nu19-Aug-14 7:08 
AnswerRe: is it possible...? Pin
Sandeep Singh Shekhawat31-Aug-14 5:17
professionalSandeep Singh Shekhawat31-Aug-14 5:17 
GeneralMy vote of 3 Pin
S.Alireza azimi10-Aug-14 20:23
memberS.Alireza azimi10-Aug-14 20:23 
GeneralRe: My vote of 3 Pin
Sandeep Singh Shekhawat31-Aug-14 5:18
professionalSandeep Singh Shekhawat31-Aug-14 5:18 
GeneralGood information at single glance.. Pin
barakath_khan2-Jun-14 20:25
memberbarakath_khan2-Jun-14 20:25 
GeneralRe: Good information at single glance.. Pin
Sandeep Singh Shekhawat21-Jul-14 6:03
professionalSandeep Singh Shekhawat21-Jul-14 6:03 
Questionnot working for me Pin
Vivekh RF24-Apr-14 1:06
professionalVivekh RF24-Apr-14 1:06 
AnswerRe: not working for me Pin
Sandeep Singh Shekhawat21-Jul-14 6:02
professionalSandeep Singh Shekhawat21-Jul-14 6:02 
QuestionHi Pin
rfid20097-Apr-14 16:12
memberrfid20097-Apr-14 16:12 
AnswerRe: Hi Pin
Sandeep Singh Shekhawat21-Jul-14 6:01
professionalSandeep Singh Shekhawat21-Jul-14 6:01 
QuestionMy Vote of 5 Pin
gangesar ramanathan28-Mar-14 10:35
membergangesar ramanathan28-Mar-14 10:35 
AnswerRe: My Vote of 5 Pin
Sandeep Singh Shekhawat28-Mar-14 18:09
professionalSandeep Singh Shekhawat28-Mar-14 18:09 
QuestionThx a lot bro :) Pin
Tobmai16-Feb-14 2:04
memberTobmai16-Feb-14 2:04 
AnswerRe: Thx a lot bro :) Pin
Sandeep Singh Shekhawat18-Feb-14 17:06
professionalSandeep Singh Shekhawat18-Feb-14 17:06 
QuestionIt was really a Great Article which helped me a Lot. Pin
Mrkraju19-Dec-13 20:14
memberMrkraju19-Dec-13 20:14 
AnswerRe: It was really a Great Article which helped me a Lot. Pin
Sandeep Singh Shekhawat19-Dec-13 23:04
professionalSandeep Singh Shekhawat19-Dec-13 23:04 
GeneralMy vote of 1 Pin
mmvr2k1111-Oct-13 2:43
membermmvr2k1111-Oct-13 2:43 
GeneralRe: My vote of 1 Pin
Sandeep Singh Shekhawat11-Oct-13 17:48
professionalSandeep Singh Shekhawat11-Oct-13 17:48 
GeneralMy vote of 1 Pin
mmvr2k1111-Oct-13 2:43
membermmvr2k1111-Oct-13 2:43 
GeneralRe: My vote of 1 Pin
Sandeep Singh Shekhawat11-Oct-13 17:48
professionalSandeep Singh Shekhawat11-Oct-13 17:48 
GeneralMy vote of 5 Pin
LoveJenny22-Aug-13 16:10
memberLoveJenny22-Aug-13 16:10 
GeneralRe: My vote of 5 Pin
Sandeep Singh Shekhawat19-Dec-13 23:05
professionalSandeep Singh Shekhawat19-Dec-13 23:05 
GeneralMy vote of 5 Pin
Akhil_Mittal19-Aug-13 23:37
groupAkhil_Mittal19-Aug-13 23:37 
GeneralRe: My vote of 5 Pin
Sandeep Singh Shekhawat19-Aug-13 23:41
memberSandeep Singh Shekhawat19-Aug-13 23:41 

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
Web01 | 2.8.150901.1 | Last Updated 30 Aug 2014
Article Copyright 2013 by Sandeep Singh Shekhawat
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid