Model的绑定。

(一)使用NameValueCollectionValueProvider

C# 对NameValueCollectionValueProvider的支持是通过下面的类实现的

// Library部分
public class NameValueCollectionValueProvider : IUnvalidatedValueProvider, IValueProvider
{
// 构造函数
public NameValueCollectionValueProvider(NameValueCollection collection, CultureInfo culture);
// 实现IValueProvider
public virtual ValueProviderResult GetValue(string key);
// 省略
} [Serializable]
public class ValueProviderResult
{
public object RawValue { get; protected set; }
public object ConvertTo(Type type); }

Library部分

下面介绍一个简单的应用

// 应用部分
//Controller中定义NameValueCollectionValueProvider 作为显示Model传递给View
NameValueCollection collection = new NameValueCollection();
collection.Add("bar.Name", "John");
collection.Add("bar.Age", "");
collection.Add("bar.Address.Street", "HongKang Street");
collection.Add("bar.Address.ZipCode", "");
NameValueCollectionValueProvider nProvider = new NameValueCollectionValueProvider(collection, CultureInfo.CurrentCulture);
var test = nProvider.GetValue("bar.Name");
return View(nProvider);

Controller中传递Model

在View中接收来自Controller的传递

@Model NameValueCollectionValueProvider

<table>
<tr>
<th colspan="2">Bar</th>
</tr>
<tr>
<td>bar.Name</td>
<td>@Model.GetValue("bar.Name").ConvertTo(typeof(string))</td>
</tr>
<tr>
<td>bar.Age</td>
<td>@Model.GetValue("bar.Age").ConvertTo(typeof(string))</td>
</tr> <tr>
<th colspan="2">Bar.Address</th>
</tr>
<tr>
<td>bar.Address.Street</td>
<td>@Model.GetValue("bar.Address.Street").ConvertTo(typeof(string))</td>
</tr>
<tr>
<td>bar.Address.ZipCode</td>
<td>@Model.GetValue("bar.Address.ZipCode").ConvertTo(typeof(string))</td>
</tr>
</table>

RazoreView

继承自NameValueCollectionValueProvider的类有下面几个:

1.1: FormValueProvider 传递Form中控件的值

@using (Html.BeginForm("TestFormValueProvider", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="text" name="testBox" value="" />
<input type="submit" value="提交" title="提交" />
}

View中提交表单

在Controller中将获取Form中提交的控件值

 public ActionResult TestFormValueProvider() {
FormValueProvider form = new FormValueProvider(ControllerContext);
var testBoxValue = form.GetValue("testBox");
var outPut = testBoxValue.ConvertTo(typeof(string));
Console.WriteLine(outPut);
return null;
}

Controller中获取

1.2: QueryStringValueProvider传递查询字符串

// HTML 代码片段
<a href="@Url.Action("TestQueryStringProvider", "Home", new { Name="John Shen", Age="32"})" title="actionTest">测试URL QueryString传递Model</a>

View中添加anchor

Controller中获取View中的<a></a>的查询字符串

public ActionResult TestQueryStringProvider()
{
QueryStringValueProvider query = new QueryStringValueProvider(ControllerContext);
var testNameQueryString = query.GetValue("Name").ConvertTo(typeof(string));
var testAgeQueryString = query.GetValue("Age").ConvertTo(typeof(string));
var testCompanyQueryString = query.GetValue("Company").ConvertTo(typeof(string));
Console.WriteLine(testNameQueryString.ToString() + testAgeQueryString.ToString() + testCompanyQueryString.ToString());
return null;
}

Controller

(二)使用DictionaryValueProvider传递Model

NameValueCollectionValueProvider的是一个不对Key进行唯一性约束的键值列表,并且其Value只能是字符串。而DictionaryValueProvider才是真正意义上的键值对。Key有唯一性约束、Value可以是任何之。继承自DictionaryValueProvider的子类有以下几种

2.1: HttpFileCollectionValueProvider上传文件的绑定

HTML:

 @using (Html.BeginForm("TestFormValueProvider", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="text" name="testBox" value="" />
<input type="submit" value="提交" title="提交" />
<input type="file" name="file1"/>
<input type="file" name="file2"/>
<input type="file" name="file3"/>
<input type="file" name="file1"/>
}

HTML代码

Controller中获取从Html中上传的文件

     HttpFileCollectionValueProvider files = new HttpFileCollectionValueProvider(ControllerContext);

            object test = files.GetValue("file1").ConvertTo(typeof(HttpPostedFileWrapper[]));
var tes = test as HttpPostedFileWrapper[]; foreach (var t in tes)
{
t.SaveAs(Server.MapPath("../Content") + "/"+t.FileName);
}

因为文件上传控件中有两个Name是file1的。所以得到的是两个文件

  

2.2: RouteDataValueProvider传递RouteData中的Values属性到View

        public ActionResult Index()
{
// Pass data in RouteDataDictionary
RouteDataValueProvider provider = new RouteDataValueProvider(ControllerContext); return View(provider);
}

Controller

View中接收来自Controller的 Model

@Model RouteDataValueProvider
<h2>Index</h2>
<h3>@Model.GetValue("controller").ConvertTo(typeof(string))</h3>
<h3>@Model.GetValue("action").ConvertTo(typeof(string))</h3>

View

2.3: ChildActionValueProvider传递RouteData中的Value到子Action中的View

MVC中有很多HTMLHelper的扩展方法用于生成当前View的子View

 // Summary:
// Represents support for calling child action methods and rendering the result
// inline in a parent view.
public static class ChildActionExtensions
{
// Summary:
// Invokes the specified child action method and returns the result as an HTML
// string.
//
// Parameters:
// htmlHelper:
// The HTML helper instance that this method extends.
//
// actionName:
// The name of the action method to invoke.
//
// Returns:
// The child action result as an HTML string.
//
// Exceptions:
// System.ArgumentNullException:
// The htmlHelper parameter is null.
//
// System.ArgumentException:
// The actionName parameter is null or empty.
//
// System.InvalidOperationException:
// The required virtual path data cannot be found.
public static MvcHtmlString Action(this HtmlHelper htmlHelper, string actionName);
//
// Summary:
// Invokes the specified child action method with the specified parameters and
// returns the result as an HTML string.
//
// Parameters:
// htmlHelper:
// The HTML helper instance that this method extends.
//
// actionName:
// The name of the action method to invoke.
//
// routeValues:
// An object that contains the parameters for a route. You can use routeValues
// to provide the parameters that are bound to the action method parameters.
// The routeValues parameter is merged with the original route values and overrides
// them.
//
// Returns:
// The child action result as an HTML string.
//
// Exceptions:
// System.ArgumentNullException:
// The htmlHelper parameter is null.
//
// System.ArgumentException:
// The actionName parameter is null or empty.
//
// System.InvalidOperationException:
// The required virtual path data cannot be found.
public static MvcHtmlString Action(this HtmlHelper htmlHelper, string actionName, object routeValues);
//
// Summary:
// Invokes the specified child action method using the specified parameters
// and returns the result as an HTML string.
//
// Parameters:
// htmlHelper:
// The HTML helper instance that this method extends.
//
// actionName:
// The name of the action method to invoke.
//
// routeValues:
// A dictionary that contains the parameters for a route. You can use routeValues
// to provide the parameters that are bound to the action method parameters.
// The routeValues parameter is merged with the original route values and overrides
// them.
//
// Returns:
// The child action result as an HTML string.
//
// Exceptions:
// System.ArgumentNullException:
// The htmlHelper parameter is null.
//
// System.ArgumentException:
// The actionName parameter is null or empty.
//
// System.InvalidOperationException:
// The required virtual path data cannot be found.
public static MvcHtmlString Action(this HtmlHelper htmlHelper, string actionName, RouteValueDictionary routeValues);
//
// Summary:
// Invokes the specified child action method using the specified controller
// name and returns the result as an HTML string.
//
// Parameters:
// htmlHelper:
// The HTML helper instance that this method extends.
//
// actionName:
// The name of the action method to invoke.
//
// controllerName:
// The name of the controller that contains the action method.
//
// Returns:
// The child action result as an HTML string.
//
// Exceptions:
// System.ArgumentNullException:
// The htmlHelper parameter is null.
//
// System.ArgumentException:
// The actionName parameter is null or empty.
//
// System.InvalidOperationException:
// The required virtual path data cannot be found.
public static MvcHtmlString Action(this HtmlHelper htmlHelper, string actionName, string controllerName);
//
// Summary:
// Invokes the specified child action method using the specified parameters
// and controller name and returns the result as an HTML string.
//
// Parameters:
// htmlHelper:
// The HTML helper instance that this method extends.
//
// actionName:
// The name of the action method to invoke.
//
// controllerName:
// The name of the controller that contains the action method.
//
// routeValues:
// An object that contains the parameters for a route. You can use routeValues
// to provide the parameters that are bound to the action method parameters.
// The routeValues parameter is merged with the original route values and overrides
// them.
//
// Returns:
// The child action result as an HTML string.
//
// Exceptions:
// System.ArgumentNullException:
// The htmlHelper parameter is null.
//
// System.ArgumentException:
// The actionName parameter is null or empty.
//
// System.InvalidOperationException:
// The required virtual path data cannot be found.
public static MvcHtmlString Action(this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues);
//
// Summary:
// Invokes the specified child action method using the specified parameters
// and controller name and returns the result as an HTML string.
//
// Parameters:
// htmlHelper:
// The HTML helper instance that this method extends.
//
// actionName:
// The name of the action method to invoke.
//
// controllerName:
// The name of the controller that contains the action method.
//
// routeValues:
// A dictionary that contains the parameters for a route. You can use routeValues
// to provide the parameters that are bound to the action method parameters.
// The routeValues parameter is merged with the original route values and overrides
// them.
//
// Returns:
// The child action result as an HTML string.
//
// Exceptions:
// System.ArgumentNullException:
// The htmlHelper parameter is null.
//
// System.ArgumentException:
// The actionName parameter is null or empty.
//
// System.InvalidOperationException:
// The required virtual path data cannot be found.
public static MvcHtmlString Action(this HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues);
//
// Summary:
// Invokes the specified child action method and renders the result inline in
// the parent view.
//
// Parameters:
// htmlHelper:
// The HTML helper instance that this method extends.
//
// actionName:
// The name of the child action method to invoke.
//
// Exceptions:
// System.ArgumentNullException:
// The htmlHelper parameter is null.
//
// System.ArgumentException:
// The actionName parameter is null or empty.
//
// System.InvalidOperationException:
// The required virtual path data cannot be found.
public static void RenderAction(this HtmlHelper htmlHelper, string actionName);
//
// Summary:
// Invokes the specified child action method using the specified parameters
// and renders the result inline in the parent view.
//
// Parameters:
// htmlHelper:
// The HTML helper instance that this method extends.
//
// actionName:
// The name of the child action method to invoke.
//
// routeValues:
// An object that contains the parameters for a route. You can use routeValues
// to provide the parameters that are bound to the action method parameters.
// The routeValues parameter is merged with the original route values and overrides
// them.
//
// Exceptions:
// System.ArgumentNullException:
// The htmlHelper parameter is null.
//
// System.ArgumentException:
// The actionName parameter is null or empty.
//
// System.InvalidOperationException:
// The required virtual path data cannot be found.
public static void RenderAction(this HtmlHelper htmlHelper, string actionName, object routeValues);
//
// Summary:
// Invokes the specified child action method using the specified parameters
// and renders the result inline in the parent view.
//
// Parameters:
// htmlHelper:
// The HTML helper instance that this method extends.
//
// actionName:
// The name of the child action method to invoke.
//
// routeValues:
// A dictionary that contains the parameters for a route. You can use routeValues
// to provide the parameters that are bound to the action method parameters.
// The routeValues parameter is merged with the original route values and overrides
// them.
//
// Exceptions:
// System.ArgumentNullException:
// The htmlHelper parameter is null.
//
// System.ArgumentException:
// The actionName parameter is null or empty.
//
// System.InvalidOperationException:
// The required virtual path data cannot be found.
public static void RenderAction(this HtmlHelper htmlHelper, string actionName, RouteValueDictionary routeValues);
//
// Summary:
// Invokes the specified child action method using the specified controller
// name and renders the result inline in the parent view.
//
// Parameters:
// htmlHelper:
// The HTML helper instance that this method extends.
//
// actionName:
// The name of the child action method to invoke.
//
// controllerName:
// The name of the controller that contains the action method.
//
// Exceptions:
// System.ArgumentNullException:
// The htmlHelper parameter is null.
//
// System.ArgumentException:
// The actionName parameter is null or empty.
//
// System.InvalidOperationException:
// The required virtual path data cannot be found.
public static void RenderAction(this HtmlHelper htmlHelper, string actionName, string controllerName);
//
// Summary:
// Invokes the specified child action method using the specified parameters
// and controller name and renders the result inline in the parent view.
//
// Parameters:
// htmlHelper:
// The HTML helper instance that this method extends.
//
// actionName:
// The name of the child action method to invoke.
//
// controllerName:
// The name of the controller that contains the action method.
//
// routeValues:
// An object that contains the parameters for a route. You can use routeValues
// to provide the parameters that are bound to the action method parameters.
// The routeValues parameter is merged with the original route values and overrides
// them.
//
// Exceptions:
// System.ArgumentNullException:
// The htmlHelper parameter is null.
//
// System.ArgumentException:
// The actionName parameter is null or empty.
//
// System.InvalidOperationException:
// The required virtual path data cannot be found.
public static void RenderAction(this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues);
//
// Summary:
// Invokes the specified child action method using the specified parameters
// and controller name and renders the result inline in the parent view.
//
// Parameters:
// htmlHelper:
// The HTML helper instance that this method extends.
//
// actionName:
// The name of the child action method to invoke.
//
// controllerName:
// The name of the controller that contains the action method.
//
// routeValues:
// A dictionary that contains the parameters for a route. You can use routeValues
// to provide the parameters that are bound to the action method parameters.
// The routeValues parameter is merged with the original route values and overrides
// them.
//
// Exceptions:
// System.ArgumentNullException:
// The htmlHelper parameter is null.
//
// System.ArgumentException:
// The actionName parameter is null or empty.
//
// System.InvalidOperationException:
// The required virtual path data cannot be found.
public static void RenderAction(this HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues);
}

MVC Library Code

首先定义一个View在它里面包含一个子的View(通过以上的扩展方法)

<div>
@Html.Action("ChildActionMethod","Test", new {Name="John", Age="32"});
</div>

接着在他所指向的Controller中我们接收这个扩展方法的ChildActionValueProvider

  public ActionResult ChildActionMethod() {
ChildActionValueProvider child = new ChildActionValueProvider(ControllerContext); return View(child);
}

改Action方法指向的View就是子View中的内容

<h3>@Model.GetValue("Name").ConvertTo(typeof(string))</h3>

<h3>@Model.GetValue("Age").ConvertTo(typeof(string))</h3>

呈现的效果类似于:

使用ValueProviderCollection传递Model。

Controller端代码

 NameValueCollection nCollection = new NameValueCollection() { };
nCollection.Add("Name", "John");
nCollection.Add("Age", "");
NameValueCollectionValueProvider provider1 = new NameValueCollectionValueProvider(nCollection,CultureInfo.CurrentCulture); Dictionary<string, string> routeData = new Dictionary<string, string>();
routeData.Add("Controller", "MyController");
routeData.Add("Action", "MyController"); DictionaryValueProvider<string> provider2 = new DictionaryValueProvider<string>(routeData, CultureInfo.CurrentCulture);
List<IValueProvider> providers = new List<IValueProvider>();
providers.Add(provider1);
providers.Add(provider2); ValueProviderCollection collection = new ValueProviderCollection(new List<IValueProvider>(providers));
return View(collection);

View中可以使用Model.GetValue("...").ConvertTo(..)的方式获取ProviderCollection中传递过来的值。虽然该Collection中包含各种Provider的类型。但是ProviderCollection提供了类似于ValueProvider的GetValues方法。 他会从当前的所有Provider中找到第一个匹配的值。

反之从View中往Controller中的传值也是一样的。

MVC 学习随笔(一)的更多相关文章

  1. Extjs MVC学习随笔01

    Extjs Mvc模式下的整个MVC框架体系即下图: 包含了Controller(实现方法层),Store(数据来源管理层),View(页面布局层).之所以用MVC我想是因为减轻针对某一页面的单一的J ...

  2. MVC学习随笔----如何在页面中添加JS和CSS文件

    http://blog.csdn.net/xxjoy_777/article/details/39050011 1.如何在页面中添加Js和CSS文件. 我们只需要在模板页中添加JS和CSS文件,然后子 ...

  3. ASP.NET MVC学习之过滤器篇(1)

    一.前言 继前面四篇ASP.NET MVC的随笔,我们继续向下学习.上一节我们学习了关于控制器的使用,本节我们将要学习如何使用过滤器控制用户访问页面. 二.正文 以下的示例建立在ASP.NET MVC ...

  4. ASP.NET MVC学习之控制器篇

    一.前言 许久之后终于可以继续我的ASP.NET MVC连载了,之前我们全面的讲述了路由相关的知识,下面我们将开始控制器和动作的讲解. ASP.NET MVC学习之路由篇幅(1) ASP.NET MV ...

  5. ASP.NET MVC学习之视图篇(1)

    一.前言 不知道还有多少读者从第一篇开始一直学习到如今,笔者也会一直坚持将ASP.NET MVC的学习完美的结束掉,然后开始写如何配合其他框架使用ASP.NET MVC的随笔.当然笔者后面的随笔如果没 ...

  6. (转)ASP.NET MVC 学习第一天

    天道酬勤0322   博客园 | 首页 | 发新随笔 | 发新文章 | 联系 | 订阅  | 管理 随笔:10 文章:0 评论:9 引用:0 ASP.NET MVC 学习第一天 今天开始第一天学习as ...

  7. ASP.NET MVC学习之控制器篇扩展性

    原文:ASP.NET MVC学习之控制器篇扩展性 一.前言 在之前的一篇随笔中已经讲述过控制器,而今天的随笔是作为之前的扩展. 二.正文 1.自定义动作方法 相信大家在开发过程一定会遇到动作方法的重名 ...

  8. ASP.NET MVC学习之模型验证详解

    ASP.NET MVC学习之模型验证篇 2014-05-28 11:36 by y-z-f, 6722 阅读, 13 评论, 收藏, 编辑 一.学习前的一句话 在这里要先感谢那些能够点开我随笔的博友们 ...

  9. ASP.NET MVC 系列随笔汇总[未完待续……]

    ASP.NET MVC 系列随笔汇总[未完待续……] 为了方便大家浏览所以整理一下,有的系列篇幅中不是很全面以后会慢慢的补全的. 学前篇之: ASP.NET MVC学前篇之扩展方法.链式编程 ASP. ...

随机推荐

  1. 开源 一行代码实现多形式多动画的推送小红点WZLBadge(iOS)-备用

    更新日志 V1.2 2015.09.25 1.UITabBarItem badge is supproted; 2.Enable change badge properties when badge ...

  2. Codeforces 519E A and B and Lecture Rooms

    http://codeforces.com/contest/519/problem/E 题意: 给出一棵树和m次询问,每次询问给出两个点,求出到这两个点距离相等的点的个数. 思路: lca...然后直 ...

  3. android使用Genymotion作为模拟器

    Genymotion模拟器的好处自然不用多说,直接来说怎么用: (1)去官方网站下载:中文或英文的: http://www.genymotion.net/ http://www.genymotion. ...

  4. 用友U8.70安装说明

    用友U8.70安装说明 U8.70安装说明一.安装前注意事项:1.       在安装U870之前,我们推荐您确保当前计算机操作系统是“干净”的,即计算机在安装过操作系统和更新过必要的系统补丁后没有安 ...

  5. vue + vue-resource 跨域访问

    使用vue + vue-resource进行数据提交,后台使用RESTful API的方式存取数据,搞了一天,终于把后台搞好了.进行联合调试时,数据不能提交,报403错误: XMLHttpReques ...

  6. IOS-沙盒机制(一 简述)

    一 IOS沙盒机制       出于安全的目的,应用程序仅仅能将自己的数据和偏好设置写入到几个特定的位置上.当应用程序被安装到设备上时,系统会为其创建一个家文件夹,这个家文件夹就是应用程序的沙盒.所以 ...

  7. Android 编程下 Activity 的创建和应用退出时的销毁

    为了确保对应用中 Activity 的创建和销毁状态进行控制,所以就需要一个全局的变量来记录和销毁这些 Activity.这里的大概思路是写一个类继承 Application,并使获取该 Applic ...

  8. Samba-ADS/WINBIND

    Samba Security = ADShttp://www.justlinux.com/forum/showt...hreadid=118288 Winbindhttp://www.justlinu ...

  9. .NET基础拾遗(4)委托和事件2

    事件 事件是对象发送的消息,以发信号通知操作的发生.操作可能是由用户交互(例如鼠标单击)引起的,也可能是由某些其他的程序逻辑触发的. 引发事件的对象称为事件发送方.捕获事件并对其作出响应的对象叫做事件 ...

  10. Jquery常用方法(转)

    原文:http://www.cnblogs.com/Chenfengtao/archive/2012/01/12/2320490.html jQuery是目前使用最广泛的javascript函数库.据 ...