从控制器动作返回Json对象到jQuery

时间:2021-05-15 21:06:42

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 json2.js) and returning a Json object from the controller. I'm able to call the action fine, but instead of being able to put the response where I want it it just opens a new window with this printed on the screen:

我正试图让它正常工作(2天了)。我正在处理一个日志,在其中调用jQuery的控制器动作,传递给它一个JSON对象(使用json2.js),并从控制器返回一个JSON对象。我可以调用这个动作,但不能把响应放到我想要的地方它只会打开一个新窗口,并将其打印在屏幕上:

{"Message":"Invalid username/password combination"}

And the URL looks like http://localhost:13719/Account/LogOn so instead of calling the action and not reloading the page it's taking the user to the controller, which isn't good.

URL看起来像http://localhost:13719/Account/LogOn,而不是调用操作,而不是重新加载页面,它将用户带到控制器,这并不好。

So now for some code, first the controller code

对于一些代码,首先是控制器代码

[HttpPost]
public ActionResult 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 FailedLoginViewModel { Message = "Invalid username/password combination" });
        else
        {
            if (!string.IsNullOrEmpty(returnUrl)) 
                return Redirect(returnUrl);
            else 
                return RedirectToAction("Index", "Home");
        }
    }
    return RedirectToAction("Index", "Home");
}

And the jQuery code

和jQuery代码

$("#signin_submit").click(function () {
    var login = getLogin();
    $.ajax({
        type: "POST",
        url: "../Account/LogOn",
        data: JSON.stringify(login),
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        error: function (xhr) {
            $("#message").text(xhr.statusText);
        },
        success: function (result) {

        }
    });
});

function getLogin() {
    var un = $("#username").val();
    var pwd = $("#password").val();
    var rememberMe = $("#rememberme").val();

    return (un == "") ? null : { Username: un, Password: pwd, RememberMe: rememberMe };
}

In case you need to see the actual login form here that is as well

如果您需要在这里看到实际的登录表单

<fieldset id="signin_menu">
    <div>
        <span id="message"></span>
    </div>
    <% Html.EnableClientValidation(); %>    
    <% using (Html.BeginForm("LogOn", "Account", FormMethod.Post, new { @id = "signin" }))
        {%>

        <% ViewContext.FormContext.ValidationSummaryId = "valLogOnContainer"; %>
        <%= Html.LabelFor(m => m.Username) %>
        <%= Html.TextBoxFor(m => m.Username, new { @class = "inputbox", @tabindex = "4", @id = "username" })%><%= Html.ValidationMessageFor(m => m.Username, "*")%>
        <p>
        <%= Html.LabelFor(m=>m.Password) %>
        <%= Html.PasswordFor(m => m.Password, new { @class = "inputbox", @tabindex = "5", @id = "password" })%><%= Html.ValidationMessageFor(m => m.Password, "*")%>
        </p>
        <p class="remember">
        <input id="signin_submit" value="Sign in" tabindex="6" type="submit"/>
        <%= Html.CheckBoxFor(m => m.RememberMe, new { @class = "inputbox", @tabindex = "7", @id = "rememberme" })%>
        <%= Html.LabelFor(m => m.RememberMe) %>
        <p class="forgot"> <a href="#" id="forgot_password_link" title="Click here to reset your password.">Forgot your password?</a> </p>
        <p class="forgot-username"> <a href="#" id="forgot_username_link" title="Fogot your login name? We can help with that">Forgot your username?</a> </p>
        </p>
        <%= Html.ValidationSummaryJQuery("Please fix the following errors.", new Dictionary<string, object> { { "id", "valLogOnContainer" } })%>
    <% } %>
</fieldset>

The login form is loaded on the main page with

登录表单被加载到主页面

<% Html.RenderPartial("LogonControl");%>

Not sure if that has any bearing on this or not but thought I'd mention it.

我不确定这是否有关系,但我想我应该提一下。

EDIT: The login form is loaded similar to the Twitter login, click a link and the form loads with the help of jQuery & CSS

编辑:登录表单与Twitter登录类似,点击链接,借助jQuery和CSS加载表单

4 个解决方案

#1


12  

Your action signature will look as follows:

你的行动签名如下:

public virtual JsonResult ActionName()
{
     var abcObj = new ABC{a=1,b=2};

     return Json(abcObj);
}

#2


10  

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

如果您使用的是MVC 2,那么您必须返回如下内容:

return Json(your_object, JsonRequestBehavior.AllowGet);

I've found it here

我发现这里

For a different usage, here is my code.

对于不同的用法,这里是我的代码。

JQuery :

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#

和c#

public JsonResult GetNames(string date)
 {
   List<Provider> list = new List<Provider>();
   // [...]
   return Json(list, JsonRequestBehavior.AllowGet);
}

#3


2  

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:

好吧,我想到了一个解决办法,我想在这里分享一下,以防有人提出一个简单的问题。而不是使用美元。我转而使用$ ajax。发布并修改了我的jQuery代码,让它看起来像这样,一切都按照我最初期望的方式运行:

$("#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.

感谢所有关注我问题的人,感谢@kerrubin,因为我不知道这个问题。

#4


2  

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.

考虑到@user350374关于如何让我的action JsonResult签名,而不是ActionResult,我做了一些修改,修改了我的原始解决方案,以使用JsonResult,并在jQuery中进行了所有的检查/重引导,而不是在操作中。

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

我的jQuery调用

$("#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

LoginResult是一个简单的类,用来保存部分。

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.

感谢提示@user35037,现在我有两种方法来解决这个问题。

#1


12  

Your action signature will look as follows:

你的行动签名如下:

public virtual JsonResult ActionName()
{
     var abcObj = new ABC{a=1,b=2};

     return Json(abcObj);
}

#2


10  

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

如果您使用的是MVC 2,那么您必须返回如下内容:

return Json(your_object, JsonRequestBehavior.AllowGet);

I've found it here

我发现这里

For a different usage, here is my code.

对于不同的用法,这里是我的代码。

JQuery :

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#

和c#

public JsonResult GetNames(string date)
 {
   List<Provider> list = new List<Provider>();
   // [...]
   return Json(list, JsonRequestBehavior.AllowGet);
}

#3


2  

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:

好吧,我想到了一个解决办法,我想在这里分享一下,以防有人提出一个简单的问题。而不是使用美元。我转而使用$ ajax。发布并修改了我的jQuery代码,让它看起来像这样,一切都按照我最初期望的方式运行:

$("#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.

感谢所有关注我问题的人,感谢@kerrubin,因为我不知道这个问题。

#4


2  

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.

考虑到@user350374关于如何让我的action JsonResult签名,而不是ActionResult,我做了一些修改,修改了我的原始解决方案,以使用JsonResult,并在jQuery中进行了所有的检查/重引导,而不是在操作中。

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

我的jQuery调用

$("#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

LoginResult是一个简单的类,用来保存部分。

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.

感谢提示@user35037,现在我有两种方法来解决这个问题。