Asp.net

ASP.NET MVC 在操作方法中刪除查詢字元串

  • May 2, 2019

我有一個如下所示的操作方法:

public ActionResult Index(string message)
{
 if (message != null)
 {
   ViewBag.Message = message;
 }
 return View();
}

發生的情況是,對此的請求的 url 將如下所示:

www.mysite.com/controller/?message=Hello%20world

但我希望它看起來只是

www.mysite.com/controller/

有沒有辦法刪除 actionmethod 中的查詢字元串?

不,除非您使用 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();
}

要麼。如果您只是使用 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();
}

引用自:https://stackoverflow.com/questions/9672843