Jquery Ajax方法傳值到action
<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數據。傳遞到的Action是/Home/MyAjax。那么在Action方法處接收的方式如下:
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(); string val3 = f["val3"].ToString(); string val4 = f["val4"].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); }
注意,aclass類的屬性名就是json的key的名字,只要符合一致,它就能匹配,不得不說強悍。
