DIV CSS 佈局教程網

jQuery Ajax 傳值到 Action 的實作方法
編輯:JQuery特效代碼     

使用 jQuery 的 $.ajax 將前端表單資料傳到後台 Action,是 Web 開發的常見需求。本文以 MVC 為例,示範如何在前端組裝 JSON 並在後台接收。

前端:送出 Ajax 請求

<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
$.ajax({
type: 'POST',
url: "/Home/MyAjax",
data: {
val1: $("#txt1").val(),
val2: $("#txt2").val(),
val3: $("#txt3").val(),
val4: $("#txt4").val(),
},
dataType: "json"
});
});
}); 
</script>
<input id="btn" type="button" value="click" />
<input id="txt1" type="text" value="" />
<input id="txt2" type="text" value="" />
<input id="txt3" type="text" value="" />
<input id="txt4" type="text" value="" />

data 以 JSON 形式傳到 /Home/MyAjax。

後台:接收參數

Action 端可以用多種方式接收,最直覺的是透過方法參數或 Request 集合:

public ActionResult MyAjax(string val1)      {
     string val2 = Request["val2"].ToString();
     string val3 = Request.Form["val3"].ToString();
     string val4 = Request.Params["val4"].ToString();
     return Content("ViewUserControl1");
}

也可以直接接收 FormCollection:

public ActionResult MyAjax(FormCollection f)      {
     string val2 = f["val2"].ToString();
     return Content("ViewUserControl1");
}

更強悍的命名匹配機制

MVC3 的一個亮點,是它基於變數命名匹配的機制,會盡可能尋找同名稱的值。因此我們可以定義一個 class:

public class aclass {
    public string val1 { set; get; }
    public string val2 { set; get; }
    public string val3 { set; get; }
    public string val4 { set; get; }
}

然後直接把參數型別設為 aclass:

public ActionResult MyAjax(aclass f)      {
     return Content(f.val1+f.val2+f.val3+f.val4);
}

只要 class 的屬性名稱與 JSON 的 key 一致,MVC 就能自動對應,相當省事。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved