zoukankan      html  css  js  c++  java
  • MVC 下 JsonResult 的使用方法(JsonRequestBehavior.AllowGet)

    MVC 默认 Request 方式为 Post。

    action
    public JsonResult GetPersonInfo()
    {
    var person = new
    {
    Name = "张三",
    Age = 22,
    Sex = "男"
    };
    return Json(person);
    }

    或者

    public JsonResult GetPersonInfo()
    {
    return Json (new{Name = "张三",Age = 22,Sex = "男"});
    }

    view

    $.ajax({
    url: "/FriendLink/GetPersonInfo",
    type: "POST",
    dataType: "json",
    data: { },
    success: function(data) {
    $("#friendContent").html(data.Name);
    }
    })

    POST 请求没问题,GET 方式请求出错:

    解决方法

    json方法有一个重构:

    protected internal JsonResult Json(object data);
    protected internal JsonResult Json(object data, JsonRequestBehavior behavior);

    我们只需要使用第二种就行了,加上一个 json请求行为为Get方式就OK了

    public JsonResult GetPersonInfo()
    {
    var person = new
    {
    Name = "张三",
    Age = 22,
    Sex = "男"
    };
    return Json(person,JsonRequestBehavior.AllowGet);
    }

    这样一来我们在前端就可以使用Get方式请求了:

    $.getJSON("/FriendLink/GetPersonInfo", null, function(data) {
    $("#friendContent").html(data.Name);
    })

  • 相关阅读:
    Kubernetes(k8s)1.12.2集群搭建
    Drools规则引擎入门指南(三)——使用Docker部署Workbench
    Drools规则引擎入门指南(二)
    网络协议 11
    网络协议 10
    网络协议 9
    网络协议 8
    网络协议 7
    网络协议 6
    网络协议 5
  • 原文地址:https://www.cnblogs.com/tomahawk/p/4036639.html
Copyright © 2011-2022 走看看