Pass Value from View to Controller

In Web based application we always need to pass value from view to controller to take input and controller to view to show output.

View to Controller data sharing

To take input from the user We have following ways to pass data from view to controller.
  • Parameter
  • Request Object
  • FormCollection
  • Model

Pass value from view to controller using Parameter

In MVC we can fetch data from view to controller using parameter. In MVC View we create html control to take input from the user. With the help of name element of html control we can access these data in controller.

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

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_name, String lname_name)
            string fname = fname_name;
            string lname = lname_name;
            Response.Write("Your Full name is= " + fname + " " + lname);

            return View();


Now execute this code

Output when method set as Get

As you can see that we can fetch data in controller. So after fetching data we can also store in the database.

No comments:

Post a Comment