wil*_*lvv 13 asp.net asp.net-mvc routing query-string
我有一个看起来像这样的动作方法:
public ActionResult Index(string message)
{
if (message != null)
{
ViewBag.Message = message;
}
return View();
}
Run Code Online (Sandbox Code Playgroud)
发生的事情是,对此请求的URL将如下所示:
www.mysite.com/controller/?message=Hello%20world
Run Code Online (Sandbox Code Playgroud)
但我希望它只是看起来
www.mysite.com/controller/
Run Code Online (Sandbox Code Playgroud)
有没有办法删除actionmethod中的查询字符串?
nas*_*ski 20
不,除非您使用POST方法,否则必须以某种方式传递信息.替代方案可以是使用中间类.
// this would work if you went to controller/SetMessage?message=hello%20world
public ActionResult SetMessage(string message)
{
ViewBag.Message = message ?? "";
return RedirectToAction("Index");
}
public ActionResult Index()
{
ViewBag.Message = TempData["message"] != null ? TempData["message"] : "";
return View();
}
Run Code Online (Sandbox Code Playgroud)
要么.如果您只是使用POST
//your view:
@using(Html.BeginForm())
{
@Html.TextBox("message")
<input type="submit" value="submit" />
}
[HttpGet]
public ActionResult Index()
{ return View(); }
[HttpPost]
public ActionResult Index(FormCollection form)
{
ViewBag.Message = form["message"];
return View();
}
Run Code Online (Sandbox Code Playgroud)
您可以通过在 Razor 视图中添加一些 JavaScript 来删除查询字符串。
@section scripts{
<script>
if (location.href.includes('?')) {
history.pushState({}, null, location.href.split('?')[0]);
}
</script>
}
Run Code Online (Sandbox Code Playgroud)
如果您导航到页面
www.mysite.com/controller/?message=Hello%20world
Run Code Online (Sandbox Code Playgroud)
然后就会显示
www.mysite.com/controller/
Run Code Online (Sandbox Code Playgroud)
在浏览器中。
大多数现代浏览器都支持这一点(browser support)。
| 归档时间: |
|
| 查看次数: |
31729 次 |
| 最近记录: |