学习编程最主要的就是数据交互,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视图代码

     <form action="/stu/modify" method="post">
<input type="hidden" name="Id" value="@Model.Id" />
<table>
<tr>@ViewBag
<td>姓名:</td>
<td><input type="text" name="Name" value="@Model.Name" /></td>
</tr>
<tr>
<td>班级:</td>
<td>
<td><input type="text" name="ClassName" value="@Model.ClassName" /></td>
</td>
</tr>
</table>
<input type="submit" value="确定" />
</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对象

 public ActionResult Modify2(FormCollection from)
{
return from["Name"]
}

③Ajax异步提交

View视图代码

 <form id="fData">
<table id="tbData">
<tr>
<td>姓名:<input type="hidden" id="Id" name="Id" /></td>
<td><input id="Name" type="text" name="Name" /></td>
</tr>
<tr>
<td>班级:</td>
<td>
<input id="ClassName" type="text" name="ClassName" />
</td>
</tr>
<tr>
<td>性别:</td>
<td>
<input type="radio" id="GenderM" name="Gender" value="男" />男
<input type="radio" id="GenderF" name="Gender" value="女" checked />女
</td>
</tr>
<tr>
<td colspan="">
<input type="button" id="btnSure" value="确 定"/>
<input type="button" id="btnCancel" value="取 消"/>
</td>
</tr>
</table>
</form>

Ajax代码

     function DoModify() {
//1、可以通过Html标签ID属性获取数据,然后拼接josn格式数据
//2、使用serialize()只针对form对象可用
var data = $("#fData").serialize();
$.post("/Stu/Modify", data, function (jsonObj) {
if (jsonObj.Statu == "ok") {
...
}
}, "json");
}

④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 类型的视图 就叫做强类型视图)

 @using (Html.BeginForm("ModifyPage", "Stu", FormMethod.Post))
{
@*@Html.TextBox("txtName", "我是文本框", new { style = "border:1px solid #0094ff;" });<br />*@
@*@Html.TextArea("txtContent", "我是文本域");*@
<table id="tbData">
<tr>
<td>@Html.LabelFor(s => s.Name):</td>
<td>
@*@Html.TextBoxFor(s=>s.Name)*@
@Html.EditorFor(s => s.Name)
@*@Html.ValidationMessageFor(s => s.Name)*@
</td>
</tr>
<tr>
<td>@Html.LabelFor(s=>s.CId):</td>
<td>
@Html.DropDownListFor(s=>s.CId,ViewBag.selList as IEnumerable<SelectListItem>)
@*@Html.DropDownList("CId",ViewBag.selList as IEnumerable<SelectListItem>)*@
</td>
</tr>
<tr>
<td>@Html.LabelFor(s=>s.Gender):</td>
<td>
<!--生成 单选按钮的 方法,会根据 属性值 与 默认值 比较,如果相等,则设置为 选中!-->
<!-- 也就是说,只要 当前Model中的Gender属性值,与 某个 单选按钮方法 设置的 value值一样,则自动设置为选中! -->
@Html.RadioButtonFor(s => s.Gender, "男") 男
@Html.RadioButtonFor(s=>s.Gender,"女") 女
</td>
</tr>
<tr>
<td colspan="">
<input type="submit" id="btnSure" value="确 定"/>
<input type="button" id="btnCancel" value="取 消"/>
</td>
</tr>
</table>
@Html.ValidationSummary()
}

上面View视图在使用htmlHepler方法生成HTML标签时,会自动把对象的属性名写入到HTML标签的name属性名(即HTML标签的name属性=对象的属性名,<input type = "text" name = "obName" value="@Model.obName">)

在提交时,就会把画面上所有数据都封装到model对象中,并传递到Controller控制器Action方法中。

Controller控制器Action方法

         [HttpPost]
public ActionResult ModifyPage(Models.Student model)
{
//服务器端 验证(根据实体类属性的 验证特性来检查)
if (!ModelState.IsValid)
{
return Content("数据有误~!请不要恶意禁用浏览器脚本~~~!");
}
try
{
DbEntityEntry entry = db.Entry<Models.Student>(model);
entry.State = System.Data.EntityState.Unchanged; entry.Property("Name").IsModified = true;
entry.Property("CId").IsModified = true;
entry.Property("Gender").IsModified = true; db.SaveChanges();
return Content("<script>alert('修改成功~');window.location='/Stu/Index';</script>");
}
catch (Exception ex)
{
return Content("<script>alert('失败~~~~" + ex.Message+ "');window.location='/Stu/Index';</script>");
}
}

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视图代码

 @{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script type="text/javascript" src="~/Scripts/jquery-1.7.1.min.js"></script>
<!--使用Ajax.BeginForm必须引用的js文件-->
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script type="text/javascript">
function suc(resText) {
alert(resText);
}
function err(xhr) {
alert(xhr.readyState);
}
</script>
<style type="text/css">
#imgLoad {
display:none;
}
</style>
</head>
<body>
<h1>异步表单:</h1>
@using (Ajax.BeginForm("GetDate(Controller控制器的Action方法)", "Home(Controller控制器)", new AjaxOptions()
{
HttpMethod = "post",//提交方式
OnSuccess = "suc",//js方法
OnFailure="err",//js方法
LoadingElementId = "imgLoad"//Html标签ID
})) {
<input type="text" name="txtName" />
<input type="submit" />
<div id="imgLoad">加载中~~~</div>
} </body>
</html>

Controller控制器Action方法

 /// <summary>
/// MVC 的 Ajax Form
/// </summary>
public ActionResult GetDate()
{
System.Threading.Thread.Sleep(); string str = Request.Form["txtName"];
return Content(str + "," + DateTime.Now.ToString());
}

MVC学习八:MVC View提交数据的更多相关文章

  1. .NET MVC 学习笔记(六)— 数据导入

    .NET MVC 学习笔记(六)—— 数据导入 在程序使用过程中,有时候需要新增大量数据,这样一条条数据去Add明显不是很友好,这时候最好就是有一个导入功能,导入所需要的数据,下面我们就一起来看一下导 ...

  2. AntDesign(React)学习-4 登录页面提交数据简单实现

    github代码:https://github.com/zhaogaojian/jgdemo 全国肺炎,过节期间没地方去在家学习antd. 一.感觉antd pro项目太庞大了,可以学习下结构和代码风 ...

  3. HTML&CSS基础学习笔记1.27-input提交数据

    提交数据 我们在表单上填的信息很多情况下需要提交到后台. <input>的[type]属性值为“submit”时,表示提交表单数据.它在页面的表现形式也是个按钮,点击该按钮,表单数据将会提 ...

  4. 使用WebFrom来模拟一些MVC的MODEL与View的数据交互功能

    MVC中有一点非常闪瞎人眼的功能就是,可以根据Model与View视图来直接将页面也数据模型进行绑定,那么我们在想客户端发送页面时不需要进行各种控件赋值,不需要操心怎么渲染,当客户提交表单给服务器时也 ...

  5. MVC学习笔记---MVC导出excel(数据量大,非常耗时的,异步导出)

    要在ASP.NET MVC站点上做excel导出功能,但是要导出的excel文件比较大,有几十M,所以导出比较费时,为了不影响对界面的其它操作,我就采用异步的方式,后台开辟一个线程将excel导出到指 ...

  6. MVC中Control和View之间数据传递的方式

    1:ViewBag和ViewData 具体区别不做讨论,本处只演示ViewData的具体示例: Controler代码:ViewData["Employee"] = emp; Vi ...

  7. ASP.NET MVC 学习笔记之View 和Redriect的区别

    首先先说一下Redriect 和RedirectToAction 两个没什么区别,都是向浏览器发送302 Found相应,再有浏览器向对应的url进行请求 只是参数的意义不同而已 再说Redirect ...

  8. MVC js动态生成from提交数据然后生成文件下载

    前台: 点击触发下面事件 var turnForm = document.createElement("form"); //一定要加入到body中!! document.body. ...

  9. MVC学习笔记---MVC的处理管线

    漫步ASP.NET MVC的处理管线   ASP.NET MVC从诞生到现在已经好几个年头了,这个框架提供一种全新的开发模式,更符合web开发本质.你可以很好的使用以及个性化和扩展这个框架,但这需要你 ...

随机推荐

  1. java导入excle表格,并且对表格进行相应的修改,并对表格数据进行整理,最后导出本地表格等一系列操作

    1.首先创建一个java项目 完成效果如下图所示 2.导入以下jar包 3.代码如下 其中行和列的操作是根据需求自动划分的 public class auto_date { private stati ...

  2. css3特别篇图解FlexBox

    图文转自微博网友勾三股四 一.flex-direction 二.flex-wrap 三.justify-content 四.align-items 五.align-content

  3. 51nod 1135 原根(原根)

    题意 题目链接 Sol 可以证明素数的原根不会超过他的\(\frac{1}{4}\) 那么预处理出\(P - 1\)的所有的质因数\(p_1, p_2 \dots p_k\),暴力判断一下,如果$\e ...

  4. Java类——JDBC链接、并操作MySQL数据库

    Java——MySQL数据库操作类 package pkg.src.database; import java.sql.*; public class MYSQL_DBManager { // //定 ...

  5. idea 使用 git打成jar包到 nexus

    1.使用idea生成jar包参考:http://blog.csdn.net/eastgrand/article/details/11945309 2.进入到 自己的工程目录(含有pom.xml的目录) ...

  6. c# BackGroundWorker 多线程操作的小例子 (转)

    在我们的程序中,经常会有一些耗时较长的运算,为了保证用户体验,不引起界面不响应,我们一般会采用多线程操作,让耗时操作在后台完成,完成后再进行处理或给出提示,在运行中,也会时时去刷新界面上的进度条等显示 ...

  7. 四、CentOS 安装mariadb——Linux学习笔记

    A)安装及配置 下载mariadb: yum -y install mariadb-server mariadb 开启mariadb服务: systemctl start mariadb.servic ...

  8. TcpListener、TcpClient

    1.TcpClient using System; using System.Text; using System.Net.Sockets; namespace tcpclient { class t ...

  9. slider.js 滑动和点击事件在firefox下报错 event is not defined

    在使用layui的slider滑块控件的时候,firefox遇到了event is not defined 的情况.追究原因是因为layui的layui.js 的滑块功能依赖于silder.js,而官 ...

  10. July 02nd 2017 Week 27th Sunday

    No safe wading in an unknown water. 未知水深浅,涉水有危险. Is this the theory that has been the guideline for ...