![](/img/trans.png)
[英]RedirectToAction is not working with Tempdata - ASP.net core MVC
[英]ASP.NET Core 2.1 RedirectToAction appends TempData to url
這是我的保存功能。 它在一個稱為“存儲庫”的控制器下。 當我保存新的存儲庫時,會將其追加到我的網址中:
我知道這與RedirectToAction(“ Index”,this)有關,因為當我使用Redirect(“ Index”)時,URL剛以/ Index結尾。 但是,我希望索引字被隱藏,而RedirectToAction可以做到這一點。 我該如何解決這個問題?
public IActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Save(CreateRepositoryViewModel Input)
{
if (!ModelState.IsValid)
{
return View("Create", Input);
}
var directory = directoriesController.Create(Input);
if (directory != null)
{
Input.Path = directory;
var result = repositoriesData.Save(Input);
}
else
{
TempData["Error"] = "Repository Creation" + LoggingGlobals.Error;
return RedirectToAction("Index", this);
}
TempData["Success"] = "Repository " + LoggingGlobals.Create;
return RedirectToAction("Index", this);
}
問題出在以下return語句中:
return RedirectToAction("Index", this);
根據RedirectToAction重載列表 ,第二個參數可能包含傳遞給對象的routeValues
而不是字符串:
public virtual RedirectToActionResult RedirectToAction (string actionName, object routeValues)
因此,您實際上是將ControllerBase
實例作為routeValues
參數傳遞。 因此,您應該改為提供控制器名稱:
return RedirectToAction("Index", "Repositories");
如果要與控制器名稱一起傳遞routeValues
參數,請使用RedirectToAction
和3個重載,如下所示:
return RedirectToAction("Index", "Repositories", new { parameterName = "value" });
注意:
RedirectToAction
使用HTTP GET方法,該方法將路由參數作為查詢字符串傳遞,因此viewmodel對象不適合該方法。 您應該使用另一個TempData
或Session
狀態實例將viewmodel對象傳遞給另一個控制器。
TempData["ViewModel"] = Input;
return RedirectToAction("Index", "Repositories");
另一個答案已經解決了主要問題。
我會解決
但是,我希望索引詞被隱藏
使用屬性路由,您可以設置一個空的路由模板
[Route("[controller]")]
public class RepositoriesController {
[HttpGet]
[Route("")] //GET Repositories
[Route("[action]")] //GET Repositories/Index
public IActionResult Index() {
return View();
}
//...
}
這樣,當調用return RedirectToAction("Index")
,生成的URL將是在路由模板中配置的URL。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.