ASP.NET Core MVC:如何将QueryString参数更改为"pretty"参数URL参数? [英] ASP.NET Core MVC: How to change QueryString param into "pretty" URL param?
问题描述
我的问题是美学的.我有以下控制器:
My issue is an aesthetic one. I have the following Controller:
[HttpGet("[action]/{EmployeeTypeID:int?}")]
public IActionResult FilterByType(int EmployeeTypeID = 1)
{ ... }
例如,当我走以下路线时会叫哪个:
Which is called when I go to the following routes, for example:
/Employees/FilterByType
/Employees/FilterByType/2
太好了.控制器将以下ViewModel返回到视图:
Great. The controller returns the following ViewModel to the View:
public class EmployeesByTypeViewModel
{
public IEnumerable<Employee> FilteredEmployees { get; set; }
public IEnumerable<SelectListItem> EmployeeTypes { get; set; }
public int EmployeeTypeID { get; set; }
}
在我看来,有一个下拉菜单,应应更改URL参数(以按不同的EmployeeType进行过滤):
And my view, has a dropdown that should change the URL param (in order to filter by a different EmployeeType):
@model Tiendas.Models.EmployeesByTypeViewModel
<h2>Employees</h2>
<form asp-controller="Employees" asp-action="FilterByType" method="GET">
<select asp-for="EmployeeTypeID" asp-items="Model.EmployeeTypes">
</select>
<button type="submit">Filter</button>
</form>
//code displaying filtered employees...
但是,当我在/Employees/FilterByType
并提交表单时,例如:
However, when I'm at /Employees/FilterByType
and I submit the form it results in, for example:
/Employees/FilterByType?EmployeeTypeID=3
代替:
/Employees/FilterByType/3
我想要的是什么(在功能上都可行).此外,如果我在上面输入URL,然后提交表单,则会得到以下信息:
Which is what I want (functionality wise both work). Additionally, if I type the URL above and then submit the form, I get the following:
/Employees/FilterByType/3?EmployeeTypeID=1
如何获取 pretty URL参数而不是QueryString?我正在使用属性路由.
How can I get a pretty URL param instead of the QueryString? I'm using attribute routing.
推荐答案
您有一个正在生成GET的表单.浏览器不了解您的路由定义,并且根据标准,所有表单控件的值都将添加为查询字符串值.
You have a form that is making a GET. The browser has no knowledge of your route definition and in accordance with the standards, the value of any form controls are added as query string values.
如果要生成/Employees/FilterByType/3
,则需要javascript/jquery来生成url,并需要location.href
来进行重定向,例如
If you want to generate /Employees/FilterByType/3
, then you will need javascript/jquery to generate the url, and location.href
to make the redirect, for example
$('form').submit(function(e) {
e.preventDefault(); // cancel the default action
baseUrl = '@Url.Action("FilterByType", "Employees")';
var selectedEmployee = $('#EmployeeTypeID').val();
location.href = baseUrl + '/' + selectedEmployee; // redirect
});
这篇关于ASP.NET Core MVC:如何将QueryString参数更改为"pretty"参数URL参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!