【问题标题】:Ajax Action call throws an ErrorAjax 操作调用引发错误
【发布时间】:2014-12-11 09:05:22
【问题描述】:

我的代码似乎有一点错误。但是我找不到。

所以,我正在通过我的 ajax 函数在我的控制器中调用一个动作。

var serviceURL = '/Vm/GetVMInformation';

$.ajax({
    type: "GET",
    url: serviceURL,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
        alert("This Works fine");
        $("#testDiv").html(result); // Display the partial View in this div
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert(errorThrown);
    }
});

My Action 然后返回一个局部视图和一个列表对象。

public ActionResult GetVMInformation()
{
    List<VmInfo> VMListArray = new List<VmInfo>();
    ... Code ...
    return PartialView("_List", VmList);
}

Action 被调用,部分 View 工作。我测试了它。 所以问题是,我的 ajax 函数没有成功。所以它会抛出一个错误。当我警告错误时,我只会收到“内部服务器错误”。

有人看到我的错误吗?

注意: 我的片面看法。不确定它是否重要

<!--This partial View is just for testing the ajax function-->

@model IsolutionsAzureManager.Models.VmData

<p>@Model.Name[0]</p>

更新:

所以我将函数的返回类型(现在是 JsonResult 类型)更改为 Json

    JavaScriptSerializer jss = new JavaScriptSerializer();

    string output = jss.Serialize(VmList);
    Response.Write(output);
    Response.Flush();
    Response.End();
    return Json("_List", output);

好消息:ajax 调用现在成功了。 坏消息:我仍然无法显示我的部分视图。返回值(结果)就是 [object, Object]

    success: function (result) {
        $("#testDiv").html(result);
    },

【问题讨论】:

    标签: jquery asp.net-mvc razor


    【解决方案1】:

    如果您收到 500 错误,则说明您的应用程序有问题。

    如果您收到 JS 错误,可能是因为您的 JS 期望返回 JSON,但由于您返回部分视图,因此返回内容是 HTML。您的控制器操作应将您的列表转换为 JSON 对象,并且操作返回类型应为 JsonResult。 或者您在 JS 中更改预期的结果类型。

    *更新

    您看到“对象”是因为您只是将 JSON 注入 HTML。要正确显示它,您需要使用该对象。由于它是一个序列化列表,因此您需要对其进行迭代,对每个条目执行一些操作。 像这样的

    for (var i = 0; i < result.length; i++) { 
        alert(result[i].name);
    }
    

    其中“.name”将是您的 VmInfo 类中的某个字段。

    【讨论】:

    • 所以我更新了我的问题。显示局部视图时还是有问题
    【解决方案2】:

    Internal Server Error 表示您的服务器抛出异常并响应 500 http 状态。需要调试GetVMInformation 动作看原因。

    【讨论】:

    • GetVMInformation() 似乎工作正常。我没有任何期望
    猜你喜欢
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    相关资源
    最近更新 更多