Request object in MVC

fetch data from view to controller using request

In this article I will explain how to fetch data from controls which are on View to Controller using Request. In my last article I explain the same example using FormCollection. Request objects work with both GET and POST Method.

Example of Request object

In this example I have created the Home Controller and in this I have created index view.
In this view I have created the following form in which I am taking first name and last name from the user. For each control I have set the property name. This property I will use in form collection to fetch the data.

Code of Index.cshtml

    Layout = null;

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <form method="get" action="Welcome\Index">
                <td>Enter First Name</td>
                <td><input type="text" id="fname_id" name="fname_name" /></td>
                <td>Enter Last Name</td>
                <td><input type="text" id="lname_id" name="lname_name" /></td>
                <td><input type="submit"  /></td>
In action I have set the welcome controller and index view. So I have created welcome controller and create index view.
I have fetched the data using Request and pass name property (which we set for the controls) as a key

Code of Home Controller

  using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication1.Controllers
    public class WelcomeController : Controller

        public ActionResult Index()
            string fname = Request["fname_name"];
            string lname = Request["lname_name"];
            Response.Write("Your Full name is= " + fname + " " + lname);

            return View();


Now execute this code

Output when method set as Get

Output when method set as Post

No comments:

Post a Comment