一,ViewData,ViewBagTempData

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的更多相关文章

  1. ASP.NET MVC 4.0 学习5-ActionResult

    一,Controller簡介 Controller擔任了資料傳遞的角色,負責流程控制,決定存取哪個Model以及決定顯示哪個View頁面,即ASP.NET MVC中有關於『傳遞』的任務皆由Contro ...

  2. [ASP.NET MVC 小牛之路]15 - Model Binding

    Model Binding(模型绑定)是 MVC 框架根据 HTTP 请求数据创建 .NET 对象的一个过程.我们之前所有示例中传递给 Action 方法参数的对象都是在 Model Binding ...

  3. ASP.NET MVC 4.0 学习2-留言板實現

    新增專案實現留言板功能,瞭解MVC的運行機制 1,新增專案   2,添加數據庫文件message.mdf   Ctrl+W,L 打開資料庫連接,添加存放留言的Atricle表 添加字段,後點擊&quo ...

  4. ASP.NET MVC 4.0 学习3-Model

    Model負責獲取數據庫中的資料,並對數據庫中的數據進行處理. MVC中有關 數據庫 的任務都由Model來完成,Model中對數據資料進行定義,Controller和View中都會參考到Model, ...

  5. ASP.NET MVC 4.0 学习1-C#基础语法

    1,方法多載,相同的方法名稱,不同的參數類型.數量 class Program { static void Main(string[] args) { Program newObject = new ...

  6. ASP.NET MVC 4.0 学习4-Code First

    之前我們需要用到的數據,通過添加Entity實體數據模型把數據庫中需要的Database拉到項目中如下圖, 而就是Code First就是相對於這種處理數據的方法而言的 Code First更加準確的 ...

  7. 系列文章--从零开始学习ASP.NET MVC 1.0

    从零开始学习ASP.NET MVC 1.0 (一) 开天辟地入门篇 从零开始学习 ASP.NET MVC 1.0 (二) 识别URL的Routing组件 从零开始学习 ASP.NET MVC 1.0 ...

  8. [ASP.NET MVC 小牛之路]16 - Model 验证

    上一篇博文 [ASP.NET MVC 小牛之路]15 - Model Binding 中讲了MVC在Model Binding过程中如何根据用户提交HTTP请求数据创建Model对象.在实际的项目中, ...

  9. 从零开始学习ASP.NET MVC 1.0

    转自:http://www.cnblogs.com/zhangziqiu/archive/2009/02/27/ASPNET-MVC-1.html <从零开始学习ASP.NET MVC 1.0& ...

随机推荐

  1. Scala学习笔记--抽象成员

    package com.evor.test1 class Test1 { } object Test1{ def main(args:Array[String]):Unit = { //类参数和抽象字 ...

  2. iOS开发:详解Objective-C runTime

    Objective-C总Runtime的那点事儿(一)消息机制 最近在找工作,Objective-C中的Runtime是经常被问到的一个问题,几乎是面试大公司必问的一个问题.当然还有一些其他问题也几乎 ...

  3. openFileDialog与saveFileDialog的使用

    private void btnOpen_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogR ...

  4. PowerShell 中的目录文件管理

    前面的一篇文章我们说了部分在PS中进行文件浏览的基本概念,说到了几个虚拟驱动器的概念.并没有深入的描述相关的命令,这里我们进一步对这一知识点进行描述. 2.1 管理当前工作路径/位置 在日常管理中经常 ...

  5. nm和readelf命令的区别

    其实问题的本质是对elf格式的理解问题,因为是查看so库的符号表发现的问题. 事情起因是这样的,由于我的一个程序编译的时候出现了undefined reference to “XXX”的错误,需要链接 ...

  6. Digit Stack

    Digit Stack In computer science, a stack is a particular kind of data type or collection in which th ...

  7. 单线多拨,傻瓜式openwrt单线多拨叠加速率教程

    http://bbs.pceva.com.cn/thread-98362-1-1.html

  8. c++ 12

    一.模板与继承 1.从模板类派生模板子类 2.为模板子类提供基类 二.容器和迭代器 以链表为例. 三.STL概览 1.十大容器 1)向量(vector):连续内存,后端压弹,插删低效 2)列表(lis ...

  9. Divide and Conquer.(Merge Sort) by sixleaves

    algo-C1-Introductionhtml, body {overflow-x: initial !important;}html { font-size: 14px; }body { marg ...

  10. Git服务器搭建全过程

    GitHub是一个免费托管开源代码的Git服务器,如果我们不想公开项目的源代码,又不想付费使用,那么我们可以自己搭建一台Git服务器. 下面我们就看看,如何在Ubuntu上搭建Git服务器.我们使用V ...