How to Read Values from the Querystring with ASP.NET Core

How to get query string parameter value in asp.net core?

Generally, you should rely on model-binding to access incoming values, not read them explicitly from a certain request source.

However, the correct way to read query-string values is through Request.Query instead. And in your case:

_httpContextAccessor.HttpContext.Request.Query["data"]

See Model-Binding

How do I persist all querystring values in asp.net core 3.1 mvc?

In the Index action method, you could use ViewBag or ViewData to store the current search value (the CompanyName), then transfer it to the view page:

Then, for the sort links, you could use asp-route-{value} to add the current search value as the route parameter, and bind values via the ViewData or ViewBag. Code like this:

 <a asp-action="Index" asp-route-CompanyName="@ViewData["CurrentFilter"]" asp-route-sortOrder="@ViewData["CompanyNameSortParm"]">CompanyName</a>

The sample code as below:

Models:

public class Employee
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public string CompanyName { get; set; }

}
public class Company
{
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public List<Employee> Employees { get; set; }
}
public class EmployeeVM
{
public string CompanyName { get; set; }
public List<Company> AllCompanies { get; set; }
public List<Employee> Employees { get; set; }
}

Controller:

public class CompaniesController : Controller
{
public IActionResult Index(string sortOrder, string CompanyName)
{
ViewData["CompanyNameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "companyname_desc" : "";
ViewData["CurrentFilter"] = CompanyName;

var employees = from s in repo.GetEmployees()
select s;
if (!String.IsNullOrEmpty(CompanyName))
{
employees = employees.Where(s => s.CompanyName.Contains(CompanyName));
}
switch (sortOrder)
{
case "companyname_desc":
employees = employees.OrderByDescending(s => s.CompanyName);
break;
default:
employees = employees.OrderBy(s => s.EmployeeId);
break;
}

EmployeeVM vm = new EmployeeVM();
vm.Employees = employees.ToList();
vm.AllCompanies = repo.GetAllCompanies().ToList();

return View(vm);
}
}

Index Views:

@model netcore3.Data.EmployeeVM

<form asp-controller="Companies" asp-action="Index" method="get">
<p>
<label>Company Name: </label>
<select asp-for="CompanyName" asp-items="@(new SelectList(Model.AllCompanies, "CompanyName","CompanyName"))">
<option value="">All</option>
</select>
<input type="submit" value="Find" />
</p>
</form>
<table class="table">
<thead>
<tr>
<th>
EmployeeName
</th>
<th>
<a asp-action="Index" asp-route-CompanyName="@ViewData["CurrentFilter"]" asp-route-sortOrder="@ViewData["CompanyNameSortParm"]">CompanyName</a>
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Employees)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.EmployeeName)
</td>
<td>
@Html.DisplayFor(modelItem => item.CompanyName)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.EmployeeId">Edit</a> |
<a asp-action="Details" asp-route-id="@item.EmployeeId">Details</a> |
<a asp-action="Delete" asp-route-id="@item.EmployeeId">Delete</a>
</td>
</tr>
}
</tbody>
</table>

The result like this:

Sample Image

Reference:

Tutorial: Add sorting, filtering, and paging - ASP.NET MVC with EF Core

Anchor Tag Helper in ASP.NET Core

ASP.NET Core, query string to object programmatically

You can use QueryHelpers.ParseQuery(String) to parse a query string into a dictionary.

If you want the actual same behavior as provided by the [FromQuery] attribute I'd look at the QueryParameterValueSupplier.RenderParametersFromQueryString method, which does most of the heavy-lifting. I'm not sure if this is meant to be used outside of the existing ASP.NET Core framework infrastructure.

Note that a query string is just a collection of string-based name-value pairs. There's no standard that dictates how this should be mapped to something more complex like a Java or C# class. So frameworks like ASP.NET Core build their own convention on top of that, in order to make their complex binding mechanisms work. (e.g. foo.bar[2]=123). ASP.NET Core actually has two ways of binding query strings to a model (the "MVC" way and the "jQuery" way), see JQueryKeyValuePairNormalizer.

    // This is a helper method for Model Binding over a JQuery syntax.
// Normalize from JQuery to MVC keys. The model binding infrastructure uses MVC keys.
// x[] --> x
// [] --> ""
// x[12] --> x[12]
// x[field] --> x.field, where field is not a number
private static string NormalizeJQueryToMvc(StringBuilder builder, string key)

Finally on a personal note I tend to avoid the query string for anything more complex than simple name-value pairs. When you start to pull in more complex data structures you also run into many limitations. For instance: differentiating between null and empty strings; awkward syntax for handling collections; etc. If I really must use the query string for passing along complex data structures, I fallback to a single Base64 encoded JSON-string and handle that manually within my code.

How to read the query string params of a ASP.NET raw URL?

This is probably what you're after

  Uri theRealURL = new Uri(HttpContext.Current.Request.Url.Scheme + "://" +   HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.RawUrl);

string yourValue= HttpUtility.ParseQueryString(theRealURL.Query).Get("yourParm");

How to modify form & querystring values at middleware in asp.net core?

You cannot modify the form & querystring values directly because they are read-only, you can only try to replace it.

Try to change your middleware like below:

public class TestMiddleware
{
private readonly RequestDelegate _next;

public TestMiddleware(RequestDelegate next)
{
_next = next;

}

public async Task Invoke(HttpContext httpContext)
{
var queryitems = httpContext.Request.Query.SelectMany(x => x.Value, (col, value) => new KeyValuePair<string, string>(col.Key, value)).ToList();
List<KeyValuePair<string, string>> queryparameters = new List<KeyValuePair<string, string>>();
foreach(var item in queryitems)
{
var value = item.Value.ToString().Replace("x", "y");
KeyValuePair<string, string> newqueryparameter = new KeyValuePair<string, string>(item.Key, value);
queryparameters.Add(newqueryparameter);
}

var contentType = httpContext.Request.ContentType;

if (contentType != null && contentType.Contains("multipart/form-data"))
{
var formitems = httpContext.Request.Form.SelectMany(x => x.Value, (col, value) => new KeyValuePair<string, string>(col.Key, value)).ToList();

Dictionary<string, StringValues> formparameters = new Dictionary<string, StringValues>();
foreach (var item in formitems)
{
var value = item.Value.ToString().Replace("x", "y");
formparameters.Add(item.Key, value);
};

var qb1 = new QueryBuilder(queryparameters);
var qb2 = new FormCollection(formparameters);
httpContext.Request.QueryString = qb1.ToQueryString();
httpContext.Request.Form = qb2;

var items2 = httpContext.Request.Query.SelectMany(x => x.Value, (col, value) => new KeyValuePair<string, string>(col.Key, value)).ToList();
var items3 = httpContext.Request.Form.SelectMany(x => x.Value, (col, value) => new KeyValuePair<string, string>(col.Key, value)).ToList();
}

await _next(httpContext);

}
}

public static class TestMiddlewareExtensions
{
public static IApplicationBuilder UseTest(this IApplicationBuilder builder)
{
return builder.UseMiddleware<TestMiddleware>();
}
}

Results:
Sample Image



Related Topics



Leave a reply



Submit