学习编程最主要的就是数据交互,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. IE11 F12 开发人员工具 查看 Cookie

    参考网址:Using the F12 developer tools in IE11 Step1 : IE11 => F12 打开 开发人员工具 Step2:开发人员工具 => 网络F5 ...

  2. java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.yunweather.app.db.YunWeatherDB.loadProvinces()' on a null object reference

    NullPointerException:查看自己的什么地方是否对空指针进行了操作 Attempt to invoke virtual method 'java.util.List com.yunwe ...

  3. 使用js获取URL地址栏里面的参数, 获取请求链接参数,函数定义如下

    function getUrlRequestParam(name) { var paramUrl = window.location.search.substr(1); var paramStrs = ...

  4. COGS2259 异化多肽

    传送门 听说是多项式求逆的模板题,以后不怕没地方练多项式求逆啦哈哈…… …… 我们设使用一个氨基酸能组成质量为$n$的多肽数量这个数列为$\{a_n\}$,设它的生成函数为$A(x)$,显然有 \be ...

  5. webapi datetime类型序列化成json带T且时间不对问题的解决

    在global.asax.cs里加入如下代码: protected void Application_Start() { GlobalConfiguration.Configuration.Forma ...

  6. 汉诺塔matlab实现

    Matlab的递归调用,好久不用matlab了,练练手.   global handCount; handCount = 1; huuotsun(1, 2, 3, 3)     function hu ...

  7. Android碎笔录2——按键的点击变色和圆角实现

    android的Button默认写出来之后都是方形的直角,并且点击感很不明显,只要在drawable中加上一个xml就能解决这个问题: <?xml version="1.0" ...

  8. QT5.3.1 Quick 开发(二) 项目类型的选择

    作为一个转行QT开发的新手,面对基于QML的开发时候 看到很多的项目类型感到很困惑,不知道应该怎么选择.如图: 经过研究发现QT widgets Application.QtQuick Applica ...

  9. qwewq

  10. apache2 tomat https 变成http的解决方案

    1.apache2   设置 RequestHeader set X-Forwarded-Proto "https" 2.springboot 设置 server.tomcat.p ...