【问题标题】:How do I use MVC jQuery and Ajax together in order to return Json objects如何一起使用 MVC jQuery 和 Ajax 以返回 Json 对象
【发布时间】:2011-05-31 00:17:34
【问题描述】:

我希望能够单击一个按钮,让我的控制器中的一个函数返回一个 JSON 对象,该对象可以在我的页面上使用而无需重新加载页面。

我的控制器:

//Dont know if HttpPost is right 
[HttpPost] 
public ActionResult GetPinPoints() {
    return jsonobject;
}

我希望能够调用它并让它在 AJAX 页面上返回一个 JSON 对象,这样我就不必重新加载页面。

【问题讨论】:

    标签: c# asp.net asp.net-mvc-3 razor


    【解决方案1】:

    两部分:

    1) 控制器

    public JsonResult GetPinPoints()
    {
        var stuff = DoStuff();
        return Json(stuff);
    }
    

    2) 视图(通过 JQuery)

    $('#SomeButtonId').click(function () {
    
    $.ajax({
        url: '/Controller/GetPinPoints',
        type: "POST",
        dataType: "json",
        success: function(data) {
            $('#someSuccessDiv').html(data).fadeIn();   
            //Do whatever here, just a poor mans example
        },
        error: function() {
            $('#someErrorDiv').html('Boo').fadeIn();
        }
    });
    
        return false;
    });
    

    【讨论】:

    • 啊,很高兴知道。只是因为缺少输入参数而不需要该属性还是有技术原因?不管怎样,我已经更新了我的答案。
    • contentType 应该描述输入参数(jQuery 的“数据”)的编码格式。当您使用 ASP.NET WebForms 的 ScriptServices 和 PageMethods 时,您必须使用 JSON 编码的数据参数和 application/json 的内容类型,以便从它们中获取 JSON 响应。使用 ASP.NET MVC,您可以改用 application/form-url-encoded 参数,这更常见,但仍然 respond 使用 JSON。
    【解决方案2】:

    在.ajax中,使用post方法调用该方法:

    [HttpPost] 
    public ActionResult GetPinPoints() {
        var obj = new ...
        return Json(obj);
    }
    

    【讨论】:

      【解决方案3】:

      最简单的方法是使用protected Json method on the Controller class。这将获取一个对象并使用JsonResult 返回它的 JSON 表示形式。

      使用您的示例:

      public ActionResult GetPinPoints() {
          return Json(jsonobject);
      }
      

      如果您不喜欢 ASP.NET MVC 将您的对象序列化为 JSON 的方式,您可以自己做,创建一个 ActionResult,它将获取您的对象(或您构建的 JSON)并将内容写回响应流。只要确保您发回的ContentTypeapplication/jsontext/javascript 类型即可。

      从那里,您可以调用getJSON in jQuery 来获取结果,然后根据需要使用对象。

      请注意,如果您不需要任何过于复杂的东西,或者您的设计不需要它,则不需要HttpPostAttribute

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多