Ajax Redirect to Page instead of Updating Target

后端 未结 1 1221
一个人的身影
一个人的身影 2021-01-12 21:20

I am using a partial view for login and would like to redirect the user to a new page on success and show the validation errors in the partial view if the model is invalid.

相关标签:
1条回答
  • 2021-01-12 21:47

    To perform a redirect you need to do it on the client side. So you can no longer use UpdateTargetId but you should instead use the OnSuccess option. You will also need to modify the Logon controller action so that in case of a redirect you test if you it is an ajax request and in this case return a Json object with the redirect url which will be used in javascript:

    if (ModelState.IsValid)
    {
        if (string.IsNullOrEmpty(returnUrl))
        {
            returnUrl = Url.Action("Index", "App");
        }
        if (Request.IsAjaxRequest())
        {
            return Json(new { returnUrl = returnUrl });
        }
        return Redirect(returnUrl);
    }
    

    And in the view:

    <% using (Ajax.BeginForm(
        "LogOn", 
        null, 
        new AjaxOptions { 
            HttpMethod = "POST", 
            OnSuccess = "success" 
        }, 
        new { 
            id = "SignInForm", ReturnUrl = Request.QueryString["ReturnUrl"] 
        })) { %>
            <<Page HTML Controls>>
            <input type="submit" value="Log On" />
    <% } %>
    
    <script type="text/javascript">
    function success(context) {
        var returnUrl = context.get_data().returnUrl;
        if (returnUrl) {
            window.location.href = returnUrl;
        } else {
            // TODO: update the target form element with the returned partial html
        }
    }
    </script>
    
    0 讨论(0)
提交回复
热议问题