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开发本质.你可以很好的使用以及个性化和扩展这个框架,但这需要你 ...
随机推荐
- dategrid快速录入一行数据的一波操作
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- 排序算法lowb三人组-选择排序
def get_min_pos(li): min_pos = 0 for i in range(1, len(li)): if li[i] < li[min_pos]: min_pos = i ...
- 警告: The web application [ROOT] appears to have started a thread named [Thread-48] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
1. 问题描述 tomcat跑web项目(其中依赖java项目) 出现大量上述警告 项目起不来 关键字 memory leak 内存泄漏 2. 解决方案 难道是程序写的有问题? 最终 将tomcat ...
- 移动web开发ajax缓存操作
移动web开发过程中网速是必须考虑的一个因素,所以一般是尽可能的在本地存储数据,避免弱网环境下请求数据失败导致页面没有内容的情况. 前后端分离是web开发的必然趋势,在PC端我们有时甚至为了避免aja ...
- Python-MRO和C3算法
一. python多继承 在前面的学习过程中,我们已经知道了python中类与类之间可以有继承关系,当出现x是一种y的时候就可以使用继承关系.即'is-a'关系,在继承关系中子类自动拥有父类中除了私有 ...
- sublime_key 快捷键
1.Ctrl+H :查找替换 2.Ctrl+D :选择游标所在单词,连续Ctrl+D 实现多行选择(选择与第一次选择相同的单词) 3.Ctrl+K Ctrl+D 跳过当前选择,选择下一个 4.Ctrl ...
- 【Python】raw转义字符
r"hi" 这里字符串前面加了r,是raw的意思,它表示对字符串不进行转义.为什么要加这个?你可以试试print "\bhi"和r"\bhi" ...
- 在 Mac OS X 上安装 Docker(转)
http://www.oschina.net/translate/installing-docker-on-mac-os-x?print 在 Mac OS X 上安装 Docker 注意:Docker ...
- C#获取apk版本信息
获取很多人都会问我为什么要写这个博客,原因很简单,这次研发apk版本信息的时候网上查了很多的资料都没有这方面的信息,因此这次功能完了想写下方法,如果以后博友们遇到了可以直接copy,不用花很多的时间, ...
- golang构造函数
http://blog.jobbole.com/107442/?utm_source=blog.jobbole.com&utm_medium=relatedPosts https://gocn ...