Pass parameter from URL in ASP.NET MVC application

Sourav.Kayal
Posted by in ASP.NET MVC category on for Beginner level | Points: 250 | Views : 21637 red flag

How to pass value from URL in MVC application.

Pass parameter from URL in ASP.NET MVC application

In this article we will be discussing how to pass parameter in controller from URL in MVC application. First of all create one empty MVC web project and implement below code.

Create Model Class

At first we will create one model class called Person with two properties. Then within this class we will write simple ADO.NET code to fetch data from SQLServer Database.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
 
namespace PersonModel
{
    public class Person
    {
        public String Name { get; set; }
        public String Surname { get; set; }
 
 
        SqlConnection con = new SqlConnection("Data Source=SERVERNAME\\SQL_INSTANCE;Initial Catalog=test;Integrated Security=True");
 
        public List<Person> GetPerson(int Id)
        {
            List<Person> objP = new List<Person>();
            //Person P = null;
            if (con.State == ConnectionState.Broken || con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            SqlCommand cmd = new SqlCommand("select * from person where id=" + Id, con);
            SqlDataReader rd= cmd.ExecuteReader();
            while (rd.Read())
            {
                Person p = new Person();
                p.Name = rd.GetString(1);
                p.Surname = rd.GetString(2);
                objP.Add(p);
            }
            return objP;
        }
 
    }
 
}

Within GetPerson() function we are fetching data from database and pushing it onto List in a form of object. Then we are returning entire List to controller class.

Create controller class

Here we will create controller class. The class name is PersonController  and it is inherited from Controller class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PersonModel;
namespace MVC3.Controllers
{
    public class PersonController : Controller
    {
        //
        // GET: /Person/
 
        public ActionResult Index(int Id)
        {
            Person obj = new Person();
            List<Person> Li = obj.GetPerson(Id);
            return View(Li.ToList());
        }
 
    }
}

Withing Index() action we are consuming output of Model class and returning to view. One more thing is need to observer, Index() action is getting Id as parameter and this value will get pass from URL.


Create View

It’s the time to create one simple view where we will show output of controller class. Have a look on below code.

@model IList<PersonModel.Person>
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <title>Index</title>
</head>
<body>
    <div>
    @{
        foreach(var O in Model)
        {
         <li>Name:- </li>      @O.Name;
         <li>Surname:- </li>   @O.Surname;
        }
    }
       
    </div>
</body>
</html>
 

Set default routing URL

This is the last part of configuration. We will set default URL for the project. Change routing section on Global.aspx page.

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
            routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
            new { controller = "Person", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
        }

 Here is output when we are passing 1 as parameter.

When we are passing 2 as parameter


This is our table structure


Conclusion

Here we have seen how to fetch data from database according to value passed from URL. Hope you have enjoyed it.


Page copy protected against web site content infringement by Copyscape

About the Author

Sourav.Kayal
Full Name: Sourav Kayal
Member Level: Silver
Member Status: Member,MVP
Member Since: 6/20/2013 2:09:01 AM
Country: India
Read my blog here http://ctrlcvprogrammer.blogspot.in/
http://www.dotnetfunda.com
I am .NET developer working for HelixDNA Technologies,Bangalore in healthcare domain. Like to learn new technology and programming language. Currently working in ASP.NET ,C# and other microsoft technologies.

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)