jquery - Javascript 和 MVC 返回类型

标签 jquery asp.net-mvc asp.net-mvc-3

我在 ASP.Net MVC 项目的页面中有此 JavaScript:

function showAllianceMembers_onclick() {
    var strName = $("#allianceNameTextBox").val();

    $.ajax(
    {
        type: "POST",
        url: "/Alliance/Index",
        data: "allianceName=" + strName,
        success: function (result) {
            if (result.success) {
                alert("done!");
            }
            else {
                alert("error!!");
            }
        },
        error: function (req, status, error) {
            alert(error);
        }
    });
}

如您所知,此脚本正在调用 MVC Action。这是 MVC 操作:

[HttpPost]
public ActionResult Index(string allianceName)
{
    //Populating an object containing a list (IList)

    return View(res);
}

这里的问题是 JavaScript 代码只显示带有错误消息的警报... 我的代码有什么问题?

最佳答案

在您的 Controller 操作中,您不会发送 JSON,而是发送一个简单的 View 。因此 result 变量上没有定义 .success 属性。您的 AJAX 请求如下所示:

$.ajax({
    type: "POST",
    url: "/Alliance/Index",
    data: { allianceName: strName },
    success: function (result) {
        // If you got so far the AJAX request succeeded, the result variable
        // will contain the final HTML of the rendered view
        alert("done!");
    },
    error: function (req, status, error) {
        alert(error);
    }
});

或者如果您想从 Controller 操作发送 JSON:

[HttpPost]
public ActionResult Index(string allianceName)
{
    // populate the result        
    return Json(new { success = true, result = res });
}

然后:

$.ajax({
    type: "POST",
    url: "/Alliance/Index",
    data: { allianceName: strName },
    success: function (result) {
        if (result.success) {
            // do something with result.res
            alert("done!");
        }
    },
    error: function (req, status, error) {
        alert(error);
    }
});

关于jquery - Javascript 和 MVC 返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6557741/

相关文章:

php - 有没有办法为 YouTube 播放列表中的每个视频生成单独的 YouTube 嵌入?

javascript - Jquery .insertAfter() 多次插入

javascript - HighCharts 导出隐藏滚动条

c# - 复杂模型/子模型验证 (MVC) 的最佳方法

asp.net-mvc - MVC 架构 - 重新使用相同的 View 模型进行读取和编辑

asp.net-mvc-3 - 使用 ACS 登录另一个网站后如何在网站中获取登录用户身份

c# - 如何携带在 Asp.net MVC 中选择的下拉值

javascript - jQuery 弹出窗口显示旧内容而不是新内容

asp.net-mvc - MVC - 强类型 View 被破坏

asp.net-mvc-3 - 在 MVC3 中呈现 RDL(报告服务)