MVC学习八:MVC View提交数据

学习编程最主要的就是数据交互,MVC中数据交互是怎么样的呢?

1、Controller向View传输数据在http://www.cnblogs.com/WarBlog/p/7127574.html中有提到

2、View向Controller传递数据(提交数据)又是怎么样的呢?
①URL参数提交(Get方式)-- 根据MVC路由器规则

以下是POST方式

②传统Form表单Action方法提交

③Ajax异步提交

④MVC的HtmlHelper的Form表单提交(Html.BeginForm)

⑤MVC的Ajax的异步提交(Ajax.BeginForm)

3、详细分析上述提交方式

①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方法有三种方式:

1、Request.Form["Name"]

2、注意: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");
} 

3、使用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         //1、可以通过Html标签ID属性获取数据,然后拼接josn格式数据
 3         //2、使用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表单提交

1、@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         }

2、就是使用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 } 

 

posted @ 2017-07-27 17:21  一杯水M  阅读(2758)  评论(0编辑  收藏  举报