首页 > 解决方案 > 使用MVC5从同一控制器中的不同ActionResult方法单击提交按钮后如何返回相同的url?

问题描述

我希望url在单击提交后保持不变,我不想显示ActionResult方法名称

在执行以下代码之前,我的网址是http://localhost/ProjectName/

[HttpPost]
public ActionResult ControllerSignIn(Models.SignIn signin)
{
    ViewBag.name = "John";
    return View("~/Views/Home/Index.cshtml");
}

执行上述代码后,我的网址变成了http://localhost/ProjectName/ControllerSignIn/

我也试过下面的代码

[HttpPost]
public ActionResult ControllerSignIn(Models.SignIn signin,string returnUrl)
{
    ViewBag.name = "John";
    return View(returnUrl);
}

我的部分视图代码

@using (Html.BeginForm("ControllerSignIn", "Home"))
{
    //.... some text box
    @Html.Hidden("returnUrl", this.Request.RawUrl)
   <input type="submit" class="btn btn-sm btn-primary btn-rounded" value="Login" id="btnLoginSubmit" />
}

笔记

我的观点是,无论用户在哪里登录,在他们登录后,它都必须访问相同的 url

标签: asp.net-mvcmodel-view-controllerasp.net-mvc-5

解决方案


您需要意识到 URL 决定了应该执行哪个控制器和操作。传递给 View() 的不是 URL,而是路径。此路径确定应显示哪个视图...

// no matter what you put in "SomePath", your URL will remain the same.
return View("SomePath"); 

如果要将 URL 更改为http://localhost/ProjectName/,则需要重定向到该控制器的操作:

[HttpPost]
public ActionResult ControllerSignIn(Models.SignIn signin)
{
    ViewBag.name = "John";
    /* return View("~/Views/Home/Index.cshtml"); <-- this has no effect on URL */
    return RedirectToAction("MyController", "MyAction"); // this would take you to a different URL
}

如果你想重定向到:http://localhost/ProjectName/(我假设 ProjectName 是你的控制器并且你想重定向到默认操作)......你需要返回:

return RedirectToAction("ProjectName"); // redirect to default action of ProjectName controller

推荐阅读