zoukankan      html  css  js  c++  java
  • Asp.net MVC 使用json数据格式交互

    在mvc中使用json格式的数据很简单

    在controller中有Jsonresult这个类型,可以返回json的数据

    定义类Person
    public class Person
        {
            public string Name { set;get;}
            public string Sex { set; get; }
        }

    定义一个可以调用的JsonResult
    public JsonResult Child2()
            {
               Person a = new Person(){Name="a"};
               Person b = new Person(){Name="b"};
               List<Person> list = new List<Person>();
               list.Add(a);
               list.Add(b);

               return Json(list, JsonRequestBehavior.AllowGet);
            }

    在前台的web中,可以写js方法来调用,用jquery的getjson方法
    <script type="text/javascript" language="javascript">
               function test() {
                   $.getJSON("/Home/Child2", null, function (data) {
                       for (var n = 0; n < data.length; n++) {
                           alert(data[n].Name);
                       }
                   })
               }
    /Home/Child2 这个是调用的controller中action的url路径,function(data)是回调函数,
    data就是返回的json数据对象,可以直接使用

    ------------
    传递参数的情况这样
    在/Home/Child地址中直接添加查询字符串?m=hello&n=world;
    那么public JsonResult Child2()就声明成
    public JsonResult Child2(string m,string n)
    m和n就是查询字符串中变量


    前台如何解析后台返回的json
    两个列子
     $.ajax({ url:"/UserInfoAjax",
        type:"get",
        dataType:"json",
        success:function(data){alert(data.userId);}
          });


        $.getJSON("/UserInfoAjax", function (data) {
            alert(eval(data).isStar);
        });

    本文使用Blog_Backup未注册版本导出,请到soft.pt42.com注册。

  • 相关阅读:
    张维迎:你必须知道的10个经济学原理
    艾德莱斯绸:“千年时尚”托起新产业
    Sending forms through JavaScript[form提交 form data]
    Sending form data
    Your first HTML form
    form submission
    <input type="file">
    web storm查看文件结构
    jQuery-File-Upload
    IHttpHandler
  • 原文地址:https://www.cnblogs.com/zjypp/p/2319307.html
Copyright © 2011-2022 走看看