學習編程最主要的就是數據交互,MVC中數據交互是怎麼樣的呢?javascript
一、Controller向View傳輸數據在http://www.cnblogs.com/WarBlog/p/7127574.html中有提到css
二、View向Controller傳遞數據(提交數據)又是怎麼樣的呢?
①URL參數提交(Get方式)-- 根據MVC路由器規則html
如下是POST方式java
②傳統Form表單Action方法提交jquery
③Ajax異步提交ajax
④MVC的HtmlHelper的Form表單提交(Html.BeginForm)編程
⑤MVC的Ajax的異步提交(Ajax.BeginForm)json
三、詳細分析上述提交方式瀏覽器
①URL參數提交(Get方式)服務器
View端代碼
<a href="/Stu/Modify/@stu.Id">修改</a>
路由表規則
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}",//Stu/Modify/1 defaults: new { controller = "Stu", action = "RazorView", id = UrlParameter.Optional } );
Controller控制器Action方法
[HttpGet] public ActionResult Modify(int id) { return View(stu); }
②傳統Form表單Action方法提交
View視圖代碼
1 <form action="/stu/modify" method="post"> 2 <input type="hidden" name="Id" value="@Model.Id" /> 3 <table> 4 <tr>@ViewBag 5 <td>姓名:</td> 6 <td><input type="text" name="Name" value="@Model.Name" /></td> 7 </tr> 8 <tr> 9 <td>班級:</td> 10 <td> 11 <td><input type="text" name="ClassName" value="@Model.ClassName" /></td>
12 </td> 13 </tr> 14 </table> 15 <input type="submit" value="肯定" /> 16 </form>
Controller控制器Action方法有三種方式:
一、Request.Form["Name"]
二、注意:View視圖中Html控件name屬性值和Model的屬性名一致
模型綁定:.NetMVC框架會在調用action方法前,建立參數model對象,並從請求報文中檢查看是否有與該對象屬性同名的數據,若是有則設置給該對象同名的屬性
因此能夠直接以model對象做爲參數傳遞
[HttpPost] public ActionResult Modify(Models.Student model) { //Request.Form["Name"] DbEntityEntry entry = db.Entry<Models.Student>(model); entry.State = System.Data.EntityState.Unchanged; entry.Property("Name").IsModified = true; entry.Property("CId").IsModified = true; db.SaveChanges(); return Redirect("/stu/index"); }
三、使用FormCollection對象
1 public ActionResult Modify2(FormCollection from) 2 { 3 return from["Name"] 4 }
③Ajax異步提交
View視圖代碼
1 <form id="fData"> 2 <table id="tbData"> 3 <tr> 4 <td>姓名:<input type="hidden" id="Id" name="Id" /></td> 5 <td><input id="Name" type="text" name="Name" /></td> 6 </tr> 7 <tr> 8 <td>班級:</td> 9 <td> 10 <input id="ClassName" type="text" name="ClassName" />
11 </td> 12 </tr> 13 <tr> 14 <td>性別:</td> 15 <td> 16 <input type="radio" id="GenderM" name="Gender" value="男" />男 17 <input type="radio" id="GenderF" name="Gender" value="女" checked />女 18 </td> 19 </tr> 20 <tr> 21 <td colspan="2"> 22 <input type="button" id="btnSure" value="確 定"/> 23 <input type="button" id="btnCancel" value="取 消"/> 24 </td> 25 </tr> 26 </table> 27 </form>
Ajax代碼
1 function DoModify() { 2 //一、能夠經過Html標籤ID屬性獲取數據,而後拼接josn格式數據 3 //二、使用serialize()只針對form對象可用 4 var data = $("#fData").serialize(); 5 $.post("/Stu/Modify", data, function (jsonObj) { 6 if (jsonObj.Statu == "ok") { 7 ... 8 } 9 }, "json"); 10 }
④MVC的HtmlHelper的Form表單提交
一、@using (Html.BeginForm(string actionName(Action方法名),string controllerName(Controller控制器名),FormMethod method(提交方式:Get/Post--枚舉類型),object htmlAttributes(Form標籤的屬性類))){}
注意:這個Html.BeginForm方法要結合using使用
View代碼(強類型視圖--指定了 model 類型的視圖 就叫作強類型視圖)
1 @using (Html.BeginForm("ModifyPage", "Stu", FormMethod.Post)) 2 { 3 @*@Html.TextBox("txtName", "我是文本框", new { style = "border:1px solid #0094ff;" });<br />*@ 4 @*@Html.TextArea("txtContent", "我是文本域");*@ 5 <table id="tbData"> 6 <tr> 7 <td>@Html.LabelFor(s => s.Name):</td> 8 <td> 9 @*@Html.TextBoxFor(s=>s.Name)*@ 10 @Html.EditorFor(s => s.Name) 11 @*@Html.ValidationMessageFor(s => s.Name)*@ 12 </td> 13 </tr> 14 <tr> 15 <td>@Html.LabelFor(s=>s.CId):</td> 16 <td> 17 @Html.DropDownListFor(s=>s.CId,ViewBag.selList as IEnumerable<SelectListItem>) 18 @*@Html.DropDownList("CId",ViewBag.selList as IEnumerable<SelectListItem>)*@ 19 </td> 20 </tr> 21 <tr> 22 <td>@Html.LabelFor(s=>s.Gender):</td> 23 <td> 24 <!--生成 單選按鈕的 方法,會根據 屬性值 與 默認值 比較,若是相等,則設置爲 選中!--> 25 <!-- 也就是說,只要 當前Model中的Gender屬性值,與 某個 單選按鈕方法 設置的 value值同樣,則自動設置爲選中! --> 26 @Html.RadioButtonFor(s => s.Gender, "男") 男 27 @Html.RadioButtonFor(s=>s.Gender,"女") 女 28 </td> 29 </tr> 30 <tr> 31 <td colspan="2"> 32 <input type="submit" id="btnSure" value="確 定"/> 33 <input type="button" id="btnCancel" value="取 消"/> 34 </td> 35 </tr> 36 </table> 37 @Html.ValidationSummary() 38 }
上面View視圖在使用htmlHepler方法生成HTML標籤時,會自動把對象的屬性名寫入到HTML標籤的name屬性名(即HTML標籤的name屬性=對象的屬性名,<input type = "text" name = "obName" value="@Model.obName">)
在提交時,就會把畫面上全部數據都封裝到model對象中,並傳遞到Controller控制器Action方法中。
Controller控制器Action方法
1 [HttpPost] 2 public ActionResult ModifyPage(Models.Student model) 3 { 4 //服務器端 驗證(根據實體類屬性的 驗證特性來檢查) 5 if (!ModelState.IsValid) 6 { 7 return Content("數據有誤~!請不要惡意禁用瀏覽器腳本~~~!"); 8 } 9 try 10 { 11 DbEntityEntry entry = db.Entry<Models.Student>(model); 12 entry.State = System.Data.EntityState.Unchanged; 13 14 entry.Property("Name").IsModified = true; 15 entry.Property("CId").IsModified = true; 16 entry.Property("Gender").IsModified = true; 17 18 db.SaveChanges(); 19 return Content("<script>alert('修改爲功~');window.location='/Stu/Index';</script>"); 20 } 21 catch (Exception ex) 22 { 23 return Content("<script>alert('失敗~~~~" + ex.Message+ "');window.location='/Stu/Index';</script>"); 24 } 25 }
二、就是使用BeginForm+EndForm
此方法和using(BeginForm)用法同樣。
View視圖代碼
@{Html.BeginForm("Login", "User", FormMethod.Post, new { id = "form2" });} <input type="text" /> @{Html.EndForm();}
注意:@{Html.BeginForm(string actionName(Action方法名),string controllerName(Controller控制器名),FormMethod method(提交方式:Get/Post--枚舉類型),object htmlAttributes(Form標籤的屬性類)));}標註紅色大【大括號和分號{ ;}】不加上的話,頁面生成HTML代碼中會顯示【System.Web.Mvc.Html.MvcForm】字符串。
⑤MVC的Ajax的異步提交(Ajax.BeginForm)
View視圖代碼
1 @{ 2 Layout = null; 3 } 4 5 <!DOCTYPE html> 6 7 <html> 8 <head> 9 <meta name="viewport" content="width=device-width" /> 10 <title>Index</title> 11 <script type="text/javascript" src="~/Scripts/jquery-1.7.1.min.js"></script> 12 <!--使用Ajax.BeginForm必須引用的js文件--> 13 <script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script> 14 <script type="text/javascript"> 15 function suc(resText) { 16 alert(resText); 17 } 18 function err(xhr) { 19 alert(xhr.readyState); 20 } 21 </script> 22 <style type="text/css"> 23 #imgLoad { 24 display:none; 25 } 26 </style> 27 </head> 28 <body> 29 <h1>異步表單:</h1> 30 @using (Ajax.BeginForm("GetDate(Controller控制器的Action方法)", "Home(Controller控制器)", new AjaxOptions() 31 { 32 HttpMethod = "post",//提交方式 33 OnSuccess = "suc",//js方法 34 OnFailure="err",//js方法 35 LoadingElementId = "imgLoad"//Html標籤ID 36 })) { 37 <input type="text" name="txtName" /> 38 <input type="submit" /> 39 <div id="imgLoad">加載中~~~</div> 40 } 41 42 </body> 43 </html>
Controller控制器Action方法
1 /// <summary> 2 /// MVC 的 Ajax Form 3 /// </summary> 4 public ActionResult GetDate() 5 { 6 System.Threading.Thread.Sleep(2000); 9 string str = Request.Form["txtName"]; 10 return Content(str + "," + DateTime.Now.ToString()); 11 }