【问题标题】:use of model data in ajax success在ajax成功中使用模型数据
【发布时间】:2013-06-28 15:10:39
【问题描述】:
$(document).ready(function () {
    $.ajax({
        url: 'LeadPipes/LeadCounts',
        type: 'POST',
        contentType: 'application/json',
        async: false,
        success: function (data) {
            alert(data)

        }
    });
});

我正在使用上面的 ajax 调用来获取模型,我将如何在成功函数中使用模型对象。就像我需要能够像 @model.Type 这样的视图模型一样使用数据。我怎样才能成功地使用 json 数据呢?

【问题讨论】:

    标签: c# jquery .net asp.net-mvc


    【解决方案1】:

    data 对象包含通过服务器传递的属性。

    然后您可以像这样访问它们:

     var name = data.Name;
     var testData = data.TestData;
    

    您的Action 可能如下所示:

    public JsonResult LeadCounts() 
    {
       return Json(new { name = "Darren", testData = "Testing" });
    }
    

    【讨论】:

    • 好吧,数据实际上返回了一个包含其他模型的模型。那就是问题所在。它不是我要放入 json 的东西,除非我专门设置 (new{name="Darren"})
    • 您可以深入了解模型。因此,您可以根据需要使用点访问器进行深入研究。查看我的车辆示例:jsfiddle.net/ttaCp
    • @CoreyToolis 你当然可以直接调用return Json(myComplexObject); 那只是@Darren 用来解释的一个示例匿名对象
    【解决方案2】:

    在 MVC3 中你可以这样做:

    public ActionResult LeadCounts()
    {
        var data = new { Count = 1, Something = "Something" };
    
        return Json(data, JsonRequestBehavior.AllowGet);
    }
    

    在视图中:

    $(document).ready(function () {
        $.ajax({
            url: 'LeadPipes/LeadCounts',
            type: 'POST',
            contentType: 'application/json',
            async: false,
            success: function (data) {
                alert(data.Count);
            }
        });
    });
    

    【讨论】:

    • 请注意,我明确允许GET 请求(使用sonRequestBehavior.AllowGet)。在这种情况下不需要它,因为您使用的是POST 请求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2012-04-16
    • 2017-02-08
    • 1970-01-01
    相关资源
    最近更新 更多