【问题标题】:Page is not refreshed by calling RedirectToAction调用 RedirectToAction 不刷新页面
【发布时间】:2016-03-26 08:12:47
【问题描述】:

View 我有一个链接按钮,并且有 java 脚本从视图中收集信息,然后发布到相应的操作 'GroupDeny'

@Html.ActionLink("Deny Selected", "GroupDeny", null, new { @class = "denySelectedLink" })

    @section Scripts {
      @Scripts.Render("~/bundles/jqueryval")

      <script type="text/javascript">

        $(document).on('click', '.denySelectedLink', function (e) {
          //Cancel original submission
          e.preventDefault();

          var identifiers = new Array();

          //build the identifiers . . .

          var jsonArg = JSON.stringify(identifiers);
          $.post('/LicenseAssignment/GroupDeny?licensePermissionIdentifiers=' + encodeURIComponent(jsonArg));
        });        

      </script>

然后在控制器中,GroupDeny 将更新数据库,然后 调用 RedirecToAction 以刷新视图

public class LicenseAssignmentController : Controller
{
    [HttpPost]
    public ActionResult GroupDeny(string licensePermissionIdentifiers)
    {
       // changes the DB

       return RedirectToAction("Index");
    }

  // GET: 
  public async Task<ActionResult> Index()
  {
    var model = get data from DB

    return View(model);
  }

一切似乎都按预期工作,RedirectToAction("Index") 执行后将调用 Index,并且模型更新为我观看时的日期它在调试过程中,唯一的问题是页面根本没有刷新,也就是说视图仍然保持不变,但是在我手动刷新页面后(按F5),数据将使用DB中的值进行更新

【问题讨论】:

  • AJAX 不会遵循 302 重定向。如果您想重定向使用来自 post 的标准而不是 AJAX。或者您需要捕获响应并使用 JavaScript 导航。
  • @Jasen 感谢您的回复,但我是网络开发新手,请您提供更详细的信息吗?

标签: javascript asp.net-mvc


【解决方案1】:

当我们不想想要离开页面时,我们会使用 AJAX。您的 $.post() 是一个 AJAX 请求。

既然您想要导航,请向您的页面添加一个表单

@using(Html.BeginForm("GroupDeny", "LicenseAssignment", FormMethod.Post))
{
    <input type="hidden" value=""
        name="licensePermissionIdentifiers"
        id="licensePermissionIdentifiers" />
}

现在提交此表单将导航

$(document).on('click', '.denySelectedLink', function (e) {
    e.preventDefault();  // prevent link navigation

    var identifiers = new Array();

    //build the identifiers . . 

    // populate the form values
    $("#licensePermissionIdentifiers").val(identifiers);

    $("form").submit();
});

RedirectToAction() 向浏览器返回 302 RedirectLicenseAssignment/Index,然后您点击 Index 操作。

【讨论】:

    【解决方案2】:

    由于您使用的是 Ajax,因此您必须在您的 $.post 调用返回时重定向并将您的 GroupDeny 更改为 JsonResult

    可能是这样的:

    JS

    $.post('/LicenseAssignment/GroupDeny?licensePermissionIdentifiers=' + encodeURIComponent(jsonArg), function(data){
        if(data.Success){
            //redirect
            window.location.reload();
        }else{
            //handle error
        }
    });
    

    控制器动作

    [HttpPost]
    public JsonResult GroupDeny(string licensePermissionIdentifiers)
    {
       // changes the DB
    
       return Json(new { Success = true });
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 2020-05-02
    • 2011-04-23
    • 1970-01-01
    • 2011-12-22
    相关资源
    最近更新 更多