Using Query Strings in ASP.NET CORE
If we want to pass data from one page to another page then we use query string all browser support query string.
Let’s Create a Query string and read values of it.
For showing demo I have added a New Controller with name Demo7 and 2 ActionMethod with name Create and Index also we are going to add a view of both ActionMethod.
We are going to use create action method for creating action links along with query string and index action method to read values from it.
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.
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;
}