背景:
部落格中将建構一個小示例,用于示範在ASP.NET MVC4項目中,如何使用JQuery Ajax。
步驟:
1,添加控制器(HomeController)和動作方法(Index),并為Index動作方法添加視圖(Index.cshtml),視圖中HTML如下:

輸入你的姓名:
<input type="text" id="txtName"/><br/>
輸入你的年齡:
<input type="text" id="txtAge" /><br />
<button type="button" id="btn1">送出</button>
<button type="button" id="btn2">清空</button>
<p id="display"></p>

視圖中包含兩個文本框,分别用來輸入名字和年齡,包含連個按鈕,分别用來送出資訊和清空文本框的内容,同時包含一個段落,用來顯示Ajax傳回的資料資訊。
2,在Home控制器中添加另外一個動作方(AddUsers),用來接收并處理視圖傳遞過來的資料,并傳回執行結果給視圖,代碼如下:

1 public ActionResult AddUsers()
2 {
3 var my = new MyModel();
4 string result = string.Empty;
5 if(Request.IsAjaxRequest())
6 {
7 this.UpdateModel(my);
8 string name = my.Name;
9 int age = my.Age;
10 if (age < 18) result = name+"的文章好爛啊";
11 else result = name+",記得爛也要寫";
12 }
13 return Content(result);
14 }

如代碼所示:直接用Content傳回一個字元串。
或者是傳回一個 ContentResult()對象,與上面的代碼類似(是以折疊了),代碼如下:

1 public ActionResult DoWithUsers()
2 {
3 var actionResult = default(ContentResult);
4 var my = new MyModel();
5 try
6 {
7 this.UpdateModel(my);
8 string name = my.Name;
9 int age = my.Age;
10 string temp = "";
11 if (age < 18) temp = "的文章好爛啊";
12 else temp = ",記得爛也要寫";
13 actionResult = new ContentResult()
14 {
15 Content = name + temp
16 };
17 }
18 catch(Exception ex)
19 {
20 return null;
21 }
22 return actionResult;
23 }

3,修改Jquery&Ajax代碼:

1 $(document).ready(function () {
2 $("#btn1").click(function () {
3 var data = "";
4 var name = $("#txtName").val();
5 var age = $("#txtAge").val();
6 data += "&Name=" + encodeURI(name);
7 data += "&Age=" + encodeURI(age);
8 $.ajax({
9 async: true,
10 cache: false,
11 timeout: 60 * 60 * 1000,
12 data: data,
13 type: "GET",
14 datatype: "JSON",
15 url: "/Ajax/AddUsers",
16 success:function(result)
17 {
18 $("#display").text(result);
19 },
20 error: function (result) {
21 $("#display").html("error");
22 },
23 })
24 });

4,運作效果如圖:
以上,最簡單的ASP.NET MVC4&JQuery&AJax示例完成了。
以Json方式發送Action處理後的結果:
更多的情況下,不止是傳回一個字元串,而是以Json的方式傳回結果。
5,修改Action如下:

1 public ActionResult DoWithUsers()
2 {
3 var my = new MyModel();
4 try
5 {
6 this.UpdateModel(my);
7 string name = my.Name;
8 int age = my.Age;
9 string temp = "";
10 if (age < 18) temp = "的文章好爛啊";
11 else temp = ",記得爛也要寫";
12 JavaScriptSerializer jss = new JavaScriptSerializer();
13 return Json(jss.Serialize(new { Name = name, Message = temp }), JsonRequestBehavior.AllowGet);
14 }
15 catch(Exception ex)
16 {
17 return null;
18 }
19 }

說明:JSon方法傳回一個JSonResult,而JSonResult同樣是繼承自ActionResult的。
6,修改AJax部分,代碼如下:
1 success:function(result)
2 {
3 result = JSON.parse(result);
4 $("#display").text(result.Name + result.Message);
5 },
運作效果一緻。
以上,最簡單的ASP.NET MVC4&JQuery&AJax&JSon示例完成。
摘自:https://www.cnblogs.com/SharpL/p/4641040.html