ASP.NET MVC 2.0 與jQuery中的的JSON資料互動

來源:互聯網
上載者:User

   用戶端與伺服器端的非同步互動,相信大家多用jQuery提供的ajax方法實現的。下面是摘抄的jQuery API中的Ajax函數使用說明:

  上面有一個data參數允許你傳遞發送到伺服器的資料,,jQuery會根據post或者get協議對參數data進行序列化。

  如果提交的資料使用複雜的json資料,例如:

      {UserID:1,UserInfo:{ Name:"Lily", Age:"21"}}

那麼伺服器是無法正常接收到完整的參數,因為jQuery對data的序列化,是使用了索引值對拼裝的方式。參數拼裝成  UserID=1&UserInfo=object ;  UserInfo所指向的對象被序列化成字串"object"。

  如何才能把一個複雜的object對象提交到背景action參數中呢?  此處提供一個序列化資料為json格式的json.js檔案(見源碼),其中調用了 $.toJSON(param)函數,,當然你也可以自己去寫。

 

var json = { Name: "Sherry", Age: "21" };

$("#btnJson_post").click(function () {
$.ajax({
type: "POST",
url: "/Home/AcceptJson",
dataType: 'json',
data: $.toJSON(json),
contentType: 'application/json; charset=utf-8',
success: function (msg) { alert(msg.Name); }
});
});

伺服器端 :

  Person.cs

[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}

  HomeController

[HttpPost]
public JsonResult AcceptJson(Person person)
{
return Json(new Person { Name=person.Name,Age=person.Age });
}

 

  但是伺服器端person參數無法接收資料。因為無法還原序列化資料為json格式,因此在 MVC 2.0 還需要 添加引用 Microsoft.Web.Mvc.dll,並且在Global.asax.cs檔案於Application_Start()方法最後添加如下代碼:

    ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());

  這樣 MVC便可以把 json格式的資料還原序列化,且對資料作相關處理並返回結果。 源碼下載

  另外可以參考:http://www.mikel.cn/%e5%bc%80%e5%8f%91%e7%ac%94%e8%ae%b0/%e8%bd%ac%e8%bd%bdasp-net-mvc%e4%b8%ad%e7%9a%84json-binding%e5%92%8cvalidate.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.