Query String in ASP.NET MVC


On the Visual Studio, create new ASP.NET MVC Web Application project

Select Empty Template and Core Reference is MVC




In Controllers folder, create new Controller named DemoController.cs as below:

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

namespace LearnASPNETMVCWithRealApps.Controllers
{
    public class DemoController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Demo1(string id)
        {
            int id2 = int.Parse(Request.QueryString["id2"]);
            string id3 = Request.QueryString["id3"];
            ViewBag.id = id;
            ViewBag.id2 = id2;
            ViewBag.id3 = id3;
            return View("Result");
        }

    }
}

In Views/Demo folder, create new razor views as below:

Create new view named Index.cshtml as below:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>

    <h3>Query String</h3>
    <a href="@Url.Action("Demo1", "Demo", new { id = "p01", id2 = 7, id3 = "p02" })">Multiple Parameters</a>

</body>
</html>

Create new view named Result.cshtml as below:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Result</title>
</head>
<body>

    <h3>Result View</h3>
    Id: @ViewBag.id
    <br />
    Id2: @ViewBag.id2
    <br />
    Id3: @ViewBag.id3

</body>
</html>




Access Index action in Demo controller with following url: http://localhost:49328/Demo/Index

Output

Access Demo1 action in Demo controller with following url: http://localhost:49328/Demo/Demo1/p01?id2=7&id3=p02

Output

I recommend you refer to the books below to learn more about the knowledge in this article: