ASP.NET MVC 4.0 学习6-Model Binding
一,ViewData,ViewBag與TempData
ASP.NET MVC架構中,通過繼承在Controller中的ViewData,ViewBag和TempData和View頁面進行資料的存取,並且適合於少量的資料傳遞。
1.1 ViewBag
ViewBag可以產生動態屬性,我們新建項目中看到ViewBag的使用方法:
Controller中賦值:ViewBag.Title=”首頁” View中獲取值 @ViewBag.Title
1.2 ViewData
Controller中賦值:ViewData[“message”]=”This is ViewData Value”;
View頁面中取值:@ViewData[“message”]
1.3 TempData
和ViewBag,ViewData不同的是,TempData預設把資料存放於Session,
其生命週期存在於以整個Request的範圍,可以在Controller和Controller之間做資料的傳遞
public ActionResult Index()
{
//ViewData
ViewData["ViewDataValue"] = "This is ViewData Value";
//TempData
TempData["TempDataValue"] = "This is TempData Value";
//ViewBag
ViewBag.Message = "修改此範本即可開始著手進行您的 ASP.NET MVC 應用程式。"; return View();
}
<hgroup class="title">
<h1>@ViewBag.Title.</h1>
<h2>@ViewBag.Message</h2>
<h3>@ViewData["ViewDataValue"]</h3>
<h3>@TempData["TempDataValue"]</h3> </hgroup>
二, 模型連接(Model Binding)
ASP.NET MVC中會使用模型連接(Model Binding)使Controller獲取View中的資料。
2.1簡單的模型連接
如下示例,View頁面有個id為Content的文本框,對應的Action中有同名的參數Content,這樣當Action被執行的時候程序會通過DefaultModelBinder類別把View頁面傳遞過來的資料傳入Action中的同名參數。
View:
@using(Html.BeginForm()){
<div>@Html.Label("請輸入Content內容: ")<input type="text"/ name="content"></div>
<div>@Html.Label("您輸入的內容為:")@ViewData["content"]</div>
<input type="submit" value="提交"/>
}
Action:
public ActionResult TestAction(string content)
{
ViewData["Content"] = content;
return View();
}

我們下斷點看一下,點擊提交以後,會通過簡單的數據連接模型把content文本框中的值傳遞到TestAction的參數中,然後通過ViewData["Content"]把值取出。

2.2 FormCollection
ASP.NET MVC除了簡單的模型連接取得View頁面資料外,還可以通過FormCollection來取得整個客戶端頁面的資料。
在Action中加入FormCollection參數以後即可取得表單資料。
View:
@{
ViewBag.Title = "TestAction";
}
<h2>TestAction</h2>
@using(Html.BeginForm()){
<div>@Html.Label("請輸入Content內容: ")<input type="text"/ name="content"></div>
<div>@Html.Label("您輸入的內容為:")@ViewData["content"]</div>
<input type="submit" value="提交"/>
}
Action:
//FormCollection
public ActionResult TestAction(FormCollection form)
{
ViewData["Content"] = form["content"];
return View();
}
2.3複雜模型連接
1,我們添加TestFormModel類,類中定義三個屬性
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations; namespace MvcApplication3.Models
{
public class TestFormModel
{ public string Content { get; set; } public string UserID { get; set; } public int Age { get; set; }
}
}
2,Action參數更改為TestFormModel類別,來接收View頁面傳遞過來的Form表單,
只要Form表單裏面的欄位名稱和Model類別中的屬性一一對應,即可完成接收動作
View:
@{
ViewBag.Title = "TestForm";
}
<h2>TestForm</h2>
@using (Html.BeginForm())
{
<div>
@Html.Label("请输入Content内容:")
<input name="content" type="text" />
</div>
<div>@Html.Label("请输入UserID:")<input name="UserID" type="text" /></div>
<input type="submit" value="提交" />
<div>
您提交的内容为:content= @ViewData["Content"]
<br />
userID= @ViewData["UserID"]
</div>
}
Action,記得添加引用Model
//複雜模型连接
public ActionResult TestForm(TestFormModel form)
{
ViewData["Content"] = form.Content;
ViewData["UserID"] = form.UserID; return View();
}
3,View頁面輸入的值通過Form表單以Model類的格式傳遞到Controller之後,通過ViewData讀出來

我們下斷點調試可以看到,數據的傳遞:

2.4 判斷模型驗證結果
上一個例子我們看到View中的Form表單數據默認和Model類中的屬性一一對應,這樣我們就可以把數據驗證的部分放到Model中進行處理。
Controller中在處理模型連接的時候,程序會自動處理模型驗證的工作,驗證的結果儲存與ModelState物件中。
現在我們更新Model中的屬性,前面加[Required]表示這個屬性必須有值的時候ModelState. IsValid==true
Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations; namespace MvcApplication3.Models
{
public class TestFormModel
{
[Required]
public string Content { get; set; }
[Required]
public string UserID { get; set; }
[Required]
public int Age { get; set; }
}
}
View:
@{
ViewBag.Title = "TestForm";
}
<h2>TestForm</h2>
@using (Html.BeginForm())
{
<div>
@Html.Label("请输入Content内容:")
<input name="content" type="text" />
</div>
<div>@Html.Label("请输入UserID:")<input name="UserID" type="text" /></div>
<input type="submit" value="提交" />
<div>
您提交的内容为:content= @ViewData["Content"]
<br />
userID= @ViewData["UserID"]
</div>
<div>Model中的數據驗證狀態:@ViewData["Message"]</div>
}
Action:當兩個文本框都輸入值的時候,驗證成功 否則失敗
////模型验证
public ActionResult TestForm(TestFormModel form)
{
if (ModelState.IsValid)
{
//Model中的数据符合规范
ViewData["Message"] = "驗證通過";
ViewData["Content"] = form.Content;
ViewData["UserID"] = form.UserID;
}
else
{
ViewData["Message"] = "驗證失敗";
}
return View();
}
ASP.NET MVC 4.0 学习6-Model Binding的更多相关文章
- ASP.NET MVC 4.0 学习5-ActionResult
一,Controller簡介 Controller擔任了資料傳遞的角色,負責流程控制,決定存取哪個Model以及決定顯示哪個View頁面,即ASP.NET MVC中有關於『傳遞』的任務皆由Contro ...
- [ASP.NET MVC 小牛之路]15 - Model Binding
Model Binding(模型绑定)是 MVC 框架根据 HTTP 请求数据创建 .NET 对象的一个过程.我们之前所有示例中传递给 Action 方法参数的对象都是在 Model Binding ...
- ASP.NET MVC 4.0 学习2-留言板實現
新增專案實現留言板功能,瞭解MVC的運行機制 1,新增專案 2,添加數據庫文件message.mdf Ctrl+W,L 打開資料庫連接,添加存放留言的Atricle表 添加字段,後點擊&quo ...
- ASP.NET MVC 4.0 学习3-Model
Model負責獲取數據庫中的資料,並對數據庫中的數據進行處理. MVC中有關 數據庫 的任務都由Model來完成,Model中對數據資料進行定義,Controller和View中都會參考到Model, ...
- ASP.NET MVC 4.0 学习1-C#基础语法
1,方法多載,相同的方法名稱,不同的參數類型.數量 class Program { static void Main(string[] args) { Program newObject = new ...
- ASP.NET MVC 4.0 学习4-Code First
之前我們需要用到的數據,通過添加Entity實體數據模型把數據庫中需要的Database拉到項目中如下圖, 而就是Code First就是相對於這種處理數據的方法而言的 Code First更加準確的 ...
- 系列文章--从零开始学习ASP.NET MVC 1.0
从零开始学习ASP.NET MVC 1.0 (一) 开天辟地入门篇 从零开始学习 ASP.NET MVC 1.0 (二) 识别URL的Routing组件 从零开始学习 ASP.NET MVC 1.0 ...
- [ASP.NET MVC 小牛之路]16 - Model 验证
上一篇博文 [ASP.NET MVC 小牛之路]15 - Model Binding 中讲了MVC在Model Binding过程中如何根据用户提交HTTP请求数据创建Model对象.在实际的项目中, ...
- 从零开始学习ASP.NET MVC 1.0
转自:http://www.cnblogs.com/zhangziqiu/archive/2009/02/27/ASPNET-MVC-1.html <从零开始学习ASP.NET MVC 1.0& ...
随机推荐
- stm32通用定时器中断问题
在使用stm32的通用定时器定时中断的时候,发现定时器在完成初始化配置后,定时器UIF位会立刻置位,导致在使能中断后,程序会立刻进入定时器中断. 如果设计代码时不希望定时器配置完成后,立刻进入中断,可 ...
- 消息提醒,初探Notification
1:MainActivity.java package com.example.notificationtest; import android.app.Activity; import androi ...
- 做10年Windows程序员与做10年Linux程序员的区别(附无数评论)(开源软件相当于熟读唐诗三百首,不会作诗也会吟)
如果一个程序员从来没有在linux,unix下开发过程序,一直在windows下面开发程序, 同样是工作10年, 大部分情况下与在linux,unix下面开发10年的程序员水平会差别很大.我写这篇文章 ...
- VS2010中使用QtOpenGL出现 unresolved external symbol __imp__glClear@4 referenced in function之类的错误
描述: 链接了QtOpenGL4.lib QtOpend4.lib的库啊,居然还是发生此错误. 原因是没有链接OpenGL32.lib这个库.所以,要添加这个lib 重新rebuild的一下,此类的错 ...
- 《Java程序员面试笔试宝典》之Static关键字有哪些作用
static关键字主要有两种作用:第一,只想为某特定数据类型或对象分配单一的存储空间,而与创建对象的个数无关.第二,希望某个方法或属性与类而不是对象关联在一起,也就是说,在不创建对象的情况下就可以通过 ...
- android中的本地定时推送到通知栏
一.使用系统定义的Notification 以下是使用示例代码: import android.app.Notification; import android.app.NotificationMan ...
- Hibernate框架增删改查
package cn.happy.util; import org.hibernate.Session; import org.hibernate.SessionFactory; import org ...
- 修改UISearchBar placeholder textColor
[[UILabel appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor redColor]];
- 文件系统 busybox and initramfs
1.busybox制作根文件系统 http://wenku.baidu.com/link?url=h2m_xrj6OsLiHVVhMY2e0C7WKikw_H3dZY_b4mUiW1E7AEf_q34 ...
- flexible.js字体大小诡异现象解析及解决方案
最近在做一个手机端页面时,遇到了一个奇怪的问题:字体的显示大小,与在CSS中指定的大小不一致.大家可以查看这个Demo(记得打开Chrome DevTools). 就如上图所示,你可以发现,原本指定的 ...