Query strings are a simple and effective way to pass data from one page to another via the URL. All modern browsers support query strings, making them a convenient option in ASP.NET Core web applications.
In this demo, we will:
- Create a controller named
Demo7Controller - Define two action methods:
CreateandIndex - Use the
Createmethod to generate a link with query string values - Use the
Indexmethod to read and display the passed query string values
Step 1 : Create the Demo7Controller
Add a new controller named Demo7Controller with the following code:
using Microsoft.AspNetCore.Mvc;
namespace WebApplication2.Controllers
{
public class Demo7Controller : Controller
{
public IActionResult Create()
{
return View();
}
public IActionResult Index()
{
return View();
}
}
}
On Create View we are going to add Action links with parameters.
Step 2 : Create View
On Create View we are using new tag helper for creating Action Link to pass query string. In First action Link, we are 2 parameters which are passed as Dictionary and second action link we are passing single parameter productid.
@{
Layout = null;
}
<h1>Links</h1>
<br />
@{
var parms = new Dictionary<string, string>
{
{ "ProductId", "1" },
{ "Productname", "Speaker"}
};
}
<a asp-controller="Demo7" asp-action="Index" asp-all-route-data="parms">Link 1</a>
<br />
<br />
<a asp-controller="Demo7" asp-action="Index" asp-route-ProductId="1">Link 2</a>
<br />
<br />
<a href="/Demo7/Index?ProductId=1&Productname=Speaker">Link 3</a>
Now if you run application and access Demo7 controller then you will see 2 links if you hover it then you can see query string values.
Next, we are going to read this query string parameter for that we are going to use the Index Action Method which will have 2 parameters Productid, Productname.
using Microsoft.AspNetCore.Mvc;
namespace WebApplication2.Controllers
{
public class Demo7Controller : Controller
{
public IActionResult Index(string Productid, string Productname)
{
if (Productid != null)
{
ViewBag.parameter1 = Productid;
}
if (Productname != null)
{
ViewBag.parameter2 = Productname;
}
return View();
}
}
}
After getting value from query string we are going to show values of query string parameters on index view.
@{
Layout = null;
}
<h1>Index</h1>
<br />
@if (ViewBag.parameter1 != null)
{
<text> parameter1: - </text> @ViewBag.parameter1;
}
<br />
@if (ViewBag.parameter2 != null)
{
<text> parameter2: - </text> @ViewBag.parameter2;
}