Returning Json object from controller action to jQuery

前端 未结 4 1219
[愿得一人]
[愿得一人] 2020-12-31 05:43

I\'m attempting to get this working properly (2 days now). I\'m working on a log in where I\'m calling the controller action from jQuery, passing it a JSON object (utilizing

4条回答
  •  别那么骄傲
    2020-12-31 06:17

    Thinking about what @user350374 said about making the signature of my action JsonResult instead of ActionResult I did some tinkering and modified my original solution to utilize JsonResult and did all the checking/redirecting in jQuery instead of in the action.

    My action changed to

    [HttpPost,MoveFormsScript]
    public JsonResult LogOn(LogOnModel model, string returnUrl = "")
    {
        if (ModelState.IsValid)
        {
            var login = ObjectFactory.GetInstance>();
    
            var user = login.FindOne(x => x.Login == model.Username && x.Pwd == model.Password);
    
            if (user == null)
                return Json(new LoginResult { Success = false, Message = "Invalid login" });
            else
            {
                return Json(new LoginResult
                {
                    Success = true,
                    Message = "Redirecting...",
                    ReturnUrl = (!string.IsNullOrEmpty(returnUrl)) ? returnUrl : string.Format("Account/Index/{0}", user.Photographer.Key)
                });
            }
        }
        else
        {
            return Json(new LoginResultDTO { Success = false, Message = "Incomplete fields" });
        }
    
    }
    

    And my jQuery call to

    $("#signin_submit").click(function () {
        var f = $($("form")[0]);
        f.submit(function () {
            var loginData = f.serialize();
            $.post(f.attr("action"), loginData, function (result, status) {
                if (!result.Success) {
                    $("#message").text(result.Message);
    
                    $("#username").focus();
                    $("#username").select();
                }
                else {
                    window.location.replace(result.ReturnUrl);
                }
    
            }, "json");
            return false;
        });
    });
    

    LoginResult is a simple class just to hold the parts

    public class LoginResult
    {
        public bool Success { get; set; }
        public string Message { get; set; }
        public string ReturnUrl { get; set; }
    } 
    

    Thanks for the tip @user35037, now I have 2 ways to approach this in the future.

提交回复
热议问题