asp.net core_ASP.NET MVC3 JSON数据的传递使用说明

更新时间:2018-03-29    来源:ASP.NET MVC    手机版     字体:

【www.bbyears.com--ASP.NET MVC】

ASP.NET MVC 3 中内置了对 JSON 的绑定支持,使得接收从客户端传递过来的 JSON 格式的数据变得非常简单。本篇还是以 Android 博客项目中的留言小功能来简单的说明一下具体的使用方法。先看看 Razor 视图引擎下的 HTML代码,这块主要用来显示留言的数据列表:

 代码如下
    <script id="userTemplate" type="text/html">
    ${UserName} Says: ${Content}
    </script>
   
   

当我们点击 Create 按钮时提交留言(这里为了简单,留言内容固定了),执行 jQuery Ajax 传递 JSON 格式数据,如下:

 代码如下

$("#create").click(function () {
    var contact = {
        UserName: "I love jQuery",
        Website: "http://www.google.com",
        Content: "Nice to meet you."
    };

    $.ajax({
        url: "/Contact",
        type: "POST",
        data: contact,
        dataType: "json",
        success: function (req) {
            $("#userTemplate").render(req).appendTo("#Contact");
        }
    });
});

如果你是纯 ASP.NET 开发者,没有接触过 jQuery ,那么我要强烈的建议你赶快学习 jQuery ,jQuery 在 ASP.NET MVC 3 中起着非常重要的作用,它会越来越流行。现在,你可以参考下 jQuery学习大总结(五)jQuery Ajax。这样将留言内容以JSON 结构通过 POST 方式向后台提交,ASP.NET MVC 3 Controller 中接收代码如下:

 代码如下 [HttpPost]
public ActionResult Index(Contact contact)
{
    if (ModelState.IsValid)
    {
        android.Contact.AddObject(contact);
        android.SaveChanges();
    }
    var contacts = from c in android.Contact
                    where c.IsValid == 1
                    select c;
    return Json(contacts);
}

这里没有什么新知识,如果你没有看过前边 ASP.NET MVC 3 中的添加、修改、删除操作,你可以参考下 ASP.NET MVC3 实例(六) 增加、修改和删除操作(一),接收 JSON 可见,Index()方法中,接收强类型的 Contact 对象作为参数,ASP.NET MVC 3 能够在服务器端自动绑定 JSON 格式的数据到 .NET Contact 类型,ASP.NET MVC 3 添加操作中我们已经介绍过了这种自动绑定。可见,在 ASP.NET MVC 3 中实体数据的赋值变得非常简单,有了 Contact 对象后我们进行了保存操作,这里不再多说,到这我想大家已经了解到 ASP.NET MVC 3 中接收 JSON 的方便性了。程序最后使用Json()方法,它返回了一个JSON 结构的对象,在Google


如果你对使用 Google Chrome 调试 js 还不熟悉的话,可以参考下 Google Chrome 调试 js 入门,当然你也可以使用 FireFox 的 Firebug 来调试。最后 jQuery 程序中使用微软的 jQuery Templates 插件来将 JSON 格式的留言数据显示出来,使得我们没必要再进行对返回结果的遍历显示。关于 jQuery Templates 你可以参考下微软 jQuery Templates插件的使用、jQuery插件-微软 jQuery Templates。最后的结果如下:


MVC 3 中 在返回 JSON 类型时,时间的格式会是 "/Date(1306418993027)/" ,那么我们如何转换 JSON 返回结果中的时间格式呢?如在 Controller 中返回了 JSON 结构的数据:

 代码如下

[HttpPost]
public ActionResult Index(ZComment model)
{
    return Json(model, JsonRequestBehavior.AllowGet);
}


大多数情况下我们不会采用这种形式的时间格式,自己写了点代码来处理这个问题,和大家分享一下:

 代码如下

function ChangeDateFormat(d)
 {
     var date = new Date(parseInt(d.replace("/Date(", "").replace(")/", ""), 10));
     var month = padLeft(date.getMonth() + 1,10);
     var currentDate = padLeft(date.getDate(),10);
     var hour=padLeft(date.getHours(),10);
     var minute=padLeft(date.getMinutes(),10);
     return date.getFullYear() + "-" + month + "-" + currentDate+" "+hour+":"+minute;
 }
 
function padLeft(str,min){ 
    if (str>=min)
        return str;
    else 
        return "0" +str;
}

调用方法后发现结果已是我们所需要的


至此我们清楚的看到,在 ASP.NET MVC 3 中对于 JSON 数据的接收变得非常智能,同时使用 jQuery Templates 插件使得绑定 JSON 数据变得非常简单

本文来源:http://www.bbyears.com/asp/40280.html