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视图代码
<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提交数据的更多相关文章
- .NET MVC 学习笔记(六)— 数据导入
.NET MVC 学习笔记(六)—— 数据导入 在程序使用过程中,有时候需要新增大量数据,这样一条条数据去Add明显不是很友好,这时候最好就是有一个导入功能,导入所需要的数据,下面我们就一起来看一下导 ...
- AntDesign(React)学习-4 登录页面提交数据简单实现
github代码:https://github.com/zhaogaojian/jgdemo 全国肺炎,过节期间没地方去在家学习antd. 一.感觉antd pro项目太庞大了,可以学习下结构和代码风 ...
- HTML&CSS基础学习笔记1.27-input提交数据
提交数据 我们在表单上填的信息很多情况下需要提交到后台. <input>的[type]属性值为“submit”时,表示提交表单数据.它在页面的表现形式也是个按钮,点击该按钮,表单数据将会提 ...
- 使用WebFrom来模拟一些MVC的MODEL与View的数据交互功能
MVC中有一点非常闪瞎人眼的功能就是,可以根据Model与View视图来直接将页面也数据模型进行绑定,那么我们在想客户端发送页面时不需要进行各种控件赋值,不需要操心怎么渲染,当客户提交表单给服务器时也 ...
- MVC学习笔记---MVC导出excel(数据量大,非常耗时的,异步导出)
要在ASP.NET MVC站点上做excel导出功能,但是要导出的excel文件比较大,有几十M,所以导出比较费时,为了不影响对界面的其它操作,我就采用异步的方式,后台开辟一个线程将excel导出到指 ...
- MVC中Control和View之间数据传递的方式
1:ViewBag和ViewData 具体区别不做讨论,本处只演示ViewData的具体示例: Controler代码:ViewData["Employee"] = emp; Vi ...
- ASP.NET MVC 学习笔记之View 和Redriect的区别
首先先说一下Redriect 和RedirectToAction 两个没什么区别,都是向浏览器发送302 Found相应,再有浏览器向对应的url进行请求 只是参数的意义不同而已 再说Redirect ...
- MVC js动态生成from提交数据然后生成文件下载
前台: 点击触发下面事件 var turnForm = document.createElement("form"); //一定要加入到body中!! document.body. ...
- MVC学习笔记---MVC的处理管线
漫步ASP.NET MVC的处理管线 ASP.NET MVC从诞生到现在已经好几个年头了,这个框架提供一种全新的开发模式,更符合web开发本质.你可以很好的使用以及个性化和扩展这个框架,但这需要你 ...
随机推荐
- ajax传json
需求 前台有许多字段需要用ajax传送给后台, 如果给直接将字段封装成JSON对象传给后台会很方便 解决 ajax 发送 var str = {"name":"xiaom ...
- Java finally关键字
关于finally语句块,有如下特点: 1.finally语句块可以直接和try语句块联用.try...finally... 2.try...catch...finally也可以 3.通常在final ...
- hdu 1011 Starship Troopers 经典的树形DP ****
Starship Troopers Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Other ...
- 前端学习之路之CSS (三)
Infi-chu: http://www.cnblogs.com/Infi-chu/ 创建CSS有三种方法:外部样式表.内部样式表.内联样式.优先级:内联样式>内部样式>外部样式表> ...
- html发展史简介(摘抄)
1993年,IETF,Internet工程任务组(Internet Engineering Task Force)的简写.IETF又叫互联网工程任务组,成立于1985年底,是全球互联网最具权威的技术标 ...
- Python基础-小程序练习(跳出多层循环,购物车,多级菜单,用户登录)
一. 从第3层循环直接跳出所有循环 break_flag = False count = 0 while break_flag == False: print("-第一层") wh ...
- Linux基础之-元字符
Bash中的特殊字符,键盘上能敲出来的特殊字符都有其特殊意义,强调一点:元字符是被shell解释的. 1. '',取命令的执行结果 [root@MiWiFi-R3-srv ~]# ls4.txt an ...
- OpenLayers中的图层(转载)
作者:田念明出处:http://www.cnblogs.com/nianming/本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法 ...
- 爬虫入门之Scrapy框架实战(新浪百科豆瓣)(十二)
一 新浪新闻爬取 1 爬取新浪新闻(全站爬取) 项目搭建与开启 scrapy startproject sina cd sina scrapy genspider mysina http://roll ...
- CentOS 7 Nginx+PHP环境搭建!
1.Nginx 安装 rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx. ...