ASP.NET MVC, jQuery & JSON

ASP.NET MVC has changed the way .NET developers write web applications just has jQuery has changed the way developers approach javascript.  If you haven't taken a look at either, I highly recommend checking out both.  ASP.NET MVC allows for a cleaner separation of concerns, ultimately leading to cleaner and more maintainable code.  JQuery has changed javascript by taking away a lot of the pains around using javascript, especially in the areas of ajax usage.  While this was technically possible earlier either by using other frameworks or writing a bunch of javascript yourself, jQuery has simplified this process significantly.

One method of using jQuery for ajax type calls is to bring back HTML from a page have the results fill a div or some other container.  While I don't necessarily advocate this method, it can work for quickly displaying information that you don't need to interact with.  Imagine we have a div with an id of "contentdiv" we could load HTML into this by using jQuery:

$("#contentdiv").load("/somecontenturl");

  

This would send a GET request to "/somecontenturl" on the webserver and all HTML returned would be put inside the contentdiv element and rendered in the browser.  There are several other options you can use with the load method but this is basic usage.

What if you needed to interact with the data you are getting back? There is this wonderful serialization format called JSON (JavaScript Object Notation).  It is very lightweight and is supported by both jQuery and ASP.NET MVC out of the box.  Just as it's name implies, JSON is used for representing objects in javascript like you would represent a class in C#.

Let's say we have a page that shows contact information but you need to be able to add and edit addresses data using ajax type calls.  We have a model in C#:

1 public class Address
2 {
3 public int AddressId {get; set;}
4 public string Street {get; set;}
5 public string City {get; set;}
6 public string State {get; set;}
7 public string Zip {get; set;}
8 }

 

 

We also have a ContactController in our ASP.NET MVC project that will be used to display all of the data we are after.  Our page will display all of our contact data with a list of addresses.  Each will have an edit button.  There is a click event in javascript set to the edit button that will open a jQuery dialog with an edit form for the address.  We don't have all of the data we need to fill this form, so we can use jQuery to get this.  In the edit button click event we have the following code:

1 $.post("/Contact/Address/" + addressId, "",
2 function(data){
3 $("#addressId").val(data.AddressId);
4 $("#street").val(data.Street);
5 $("#city").val(data.City);
6 $("#state").val(data.State);
7 $("#zip").val(data.Zip);    
8 }, "json");

 

To break this down, we are using the jQuery post method.  The first parameter is URL you want to get information from.  In this case we have an addressId that represents the actual AddressId on the Address class.  If addressId was "1", then our URL would be "/Contact/Address/1", which will correspond with the ASP.NET MVC Action we will look at shortly.  

The second parameter of the post method is where we would pass data to the action. Since all we have is an addressId that will get passed through the URL, we will leave this blank for the time being.  The third parameter is a callback function that is has access to the return result on success.  I am using function(data) where "data" is the actual result object. I can pass an existing function if I choose, but for the sake of simplicity will just use an inline function. In the last parameter, I am passing the data format I am expecting, which in this case is JSON.

This will execute the Address action on the ContactController, which will return the an Address instance as JSON:

view source
1 public JsonResult Address(string id)
2 {
3   Address address = DataLayer.GetAddress(id);
4 
5   JsonResult result = new JsonResult();
6   result.Data = address;
7   return result;
8 }

 

 

You have to admit that is pretty cool.  We can easily get data through ASP.NET MVC converted to JSON that is directly usable in javascript and jQuery.  If you think that is cool though, it also works the other way.  We work with our new address form and are ready to update from javascript:

view source
 1 var address = {};
 2 
 3 address.AddressId = $("#addressId").val();
 4 address.Street = $("#street").val();
 5 address.City = $("#city").val();
 6 address.State = $("#state").val();
 7 address.Zip = $("#zip").val();
 8 
 9 $.post("/Contact/SaveAddress", address, function(data) {
10   // Logic on success
11   }, "json");

 

 

Here we spin up a new address object in javascript.  Since javascript's object structure is very open, there is nothing to define other than {}.  We can start setting new properties on the javascript object as we need.  The key to note here is that the property names in the javascript object must match the properties of the C# object.  If we have done this correctly, the post call will do a post to "/Contact/SaveAddress" and the new address object will be passed through as post data.  We have our standard callback function and we are expecting JSON back.  The action method on the controller will do the work:

view source
1 public JsonResult SaveAddress(Address address)
2 {
3   DataLayer.Save(address);
4 
5   JsonResult result = new JsonResult();
6   result.Data = "Success";
7   return result;
8 }

 

 

As long as we have crafted our javascript object to be identical to the C# Address object, this just magically works.  All serialization to and from JSON is done for you and the object is passed as a parameter to the SaveAddress action method.  We can save the object or do what ever we need with it and pass a result back to the callback function.

As you can see this can make it very easy to update data in your web application without post backs and give you great flexibility over what you do with the data.  ASP.NET MVCjQuery and JSON make a perfect little combination allowing you to quickly do some pretty nifty things.  Ajax in your app couldn't really be much easier.

original url:http://dotnet.dzone.com/articles/aspnet-mvc-jquery-json

转载于:https://www.cnblogs.com/john8412/archive/2012/08/02/2619219.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值