Returning Json object from controller action to jQuery

前端 未结 4 1218
[愿得一人]
[愿得一人] 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 05:59

    Ok came up with a resolution that I thought I'd share here in case someone comes along with a simliar issue. Instead of using $.ajax I switched to using $.post and changed my jQuery code to look like this and everything works just the way I initially expected it 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);
                }
            }, "json");
            return false;
        }); 
    });
    

    Thanks to all who looked at my question, and to @kerrubin as I was unaware of that issue.

    0 讨论(0)
  • 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<IRepository<PhotographerLogin>>();
    
            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.

    0 讨论(0)
  • 2020-12-31 06:18

    If you're using MVC 2, you have to return something like this :

    return Json(your_object, JsonRequestBehavior.AllowGet);
    

    I've found it here

    For a different usage, here is my code.

    JQuery :

    $(document).ready(function () {
        $("#InputDate").live('click', function () {
            var date = $("#InputDate").val();
            if (date != "") {
                $.getJSON("/Home/GetNames",
                        { date: $("#InputDate").val() },
                        function (data) {
                            $("#ProviderName").empty();
                            // [...]
                            });
                        });
            }
        });
    });
    

    And C#

    public JsonResult GetNames(string date)
     {
       List<Provider> list = new List<Provider>();
       // [...]
       return Json(list, JsonRequestBehavior.AllowGet);
    }
    
    0 讨论(0)
  • 2020-12-31 06:22

    Your action signature will look as follows:

    public virtual JsonResult ActionName()
    {
         var abcObj = new ABC{a=1,b=2};
    
         return Json(abcObj);
    }
    
    0 讨论(0)
提交回复
热议问题