[转载]若要允许 GET 请求,请将 JsonRequestBehavior 设置为 AllowGet - 露水丛生 - 博客园

mikel阅读(2037)

[转载]若要允许 GET 请求,请将 JsonRequestBehavior 设置为 AllowGet – 露水丛生 – 博客园.

请将 JsonRequestBehavior 设置为 AllowGet

MVC 默认 Request 方式为 Post。
action

public JsonResult GetPersonInfo() {
var person = new {
Name = "张三",
Age = 22,
Sex = "男"
};
return Json(person);
}

或者

public JsonResult GetPersonInfo() {
return Json (new{Name = "张三",Age = 22,Sex = "男"});
}
view
$.ajax({
url: "/FriendLink/GetPersonInfo",
type: "POST",
dataType: "json",
data: { },
success: function(data) {
$("#friendContent").html(data.Name);
}
})

POST 请求没问题,GET 方式请求出错:

 

解决方法
json方法有一个重构:

public JsonResult GetPersonInfo() {
var person = new {
Name = "张三",
Age = 22,
Sex = "男"
};
return Json(person,JsonRequestBehavior.AllowGet);
}

这样一来我们在前端就可以使用Get方式请求了:

$.getJSON("/FriendLink/GetPersonInfo", null, function(data) {
$("#friendContent").html(data.Name);
})

[转载]再次探究Android ListView缓存机制 - xyczero - 博客园

mikel阅读(1026)

[转载]再次探究Android ListView缓存机制 – xyczero – 博客园.

概述

虽然现在5.0后Google推出了RecycleView,但在5.0 Lollipop普及前Listview仍会被广泛使用,所以打算再次探究一下Listview的源码,了解一下Listview 的构成及加载机制。

探究

enter image description here
上图简单梳理了Listview的构成及与其相关类之间的关系,并简要地列出了些重要的方法和内部类。

AdapterView

从上图可以清晰的看出Listview归根究底是继承自AdapterView。AdaterView是一个抽象类,一些最基本和通用方法或接口都是在此定义或声明的,其中一些更是开发者所常用的,诸如:

//Item Click 监听接口
/**
 * Interface definition for a callback to be invoked when an item in this
 * AdapterView has been clicked.
 */
public interface OnItemClickListener {
    ... ...
    void onItemClick(AdapterView<?> parent, View view, int position, long id);
}

//设置Adapter抽象方法
/**
 * Sets the adapter that provides the data and the views to represent the data
 * in this widget.
 *
 * @param adapter The adapter to use to create this view's content.
 */
public abstract void setAdapter(T adapter);

此外在AdapterView中实现了DataSetObserver抽象类,我们一般调用mAdapter.notifyChanged()所触发的就是DataSetObserver的onChanged()方法。关键源码如下:

class AdapterDataSetObserver extends DataSetObserver {

    private Parcelable mInstanceState = null;

    @Override
    public void onChanged() {
        mDataChanged = true;
        mOldItemCount = mItemCount;
        mItemCount = getAdapter().getCount();
        ... ...
    }

    @Override
    public void onInvalidated() {
        mDataChanged = true;
		... ...
    }
    ... ...
}

AbsListView

AbsListView是继承自AdapterView,在该类中实现了一个非常重要的内部类RecycleBin,内部类RecycleBin其 实就是AbsListView缓存机制的核心类,它的作用是管理AbsListView的item存储和取得。AbsListview的缓存分为两级,第 一级为activeView,第二级为scrapview。二者的间的转换主要是在layoutChildren()方法进行(该抽象方法在 LisView中实现),具体分析见如下源码:

@Override
protected void layoutChildren() {
... ...
//说明RecycleBin并不缓存HeadView和FooterView
// Don't put header or footer views into the Recycler. 
//Those are already cached in mHeaderViews;
        if (dataChanged) {
            //如果data改变了,则当前所有childView都添加至mScrapViews;
            for (int i = 0; i < childCount; i++) {
                recycleBin.addScrapView(getChildAt(i), firstPosition+i);
                if (ViewDebug.TRACE_RECYCLER) {
                    ViewDebug.trace(getChildAt(i),
                            ViewDebug.RecyclerTraceType.MOVE_TO_SCRAP_HEAP, index, i);
                }
            }
        } else {
            //若data未改变,即第一次加载时,根据当前childCount数量对mArchiveViews赋值。
            recycleBin.fillActiveViews(childCount, firstPosition);
        }
        ... ...
         switch (mLayoutMode) {
         ... ...(在switch条件中执行makeAndAddView函数)
         }
         // Flush any cached views that did not get reused above
         //执行makeAndAddView函数后将需要显示的item view已添加至ListView中,
         //所以跳出siwtch后会将缓存的mActiveViews全部转换为mScrapViews。
        recycleBin.scrapActiveViews();
        ... ...
}

同时AbsListview中定义了一个ObtainView方法,一般地当Listview加载时若发现没有可复用的itemView时要么从 RecycleBin中转换ScrapView都要么是通过mAdapter.getView()获取新的itemView,ObtainView方法就 是专门用来处理上述的两种情况,具体分析如下:

View obtainView(int position, boolean[] isScrap) {
	... ...
	scrapView = mRecycler.getScrapView(position);
	View child;
	//若scrapView不为空,则将scrapView转换为可复用的itemView
    if (scrapView != null) {
       ... ...
        child = mAdapter.getView(position, scrapView, this);
        ... ...
     }else{
     //若scrapView为空,则通过adapter.getView()函数获取新的ItemView
      child = mAdapter.getView(position, null, this);
      ... ...
     }
}

结语

OK,今天就先总结这么多了,不足之处欢迎指出。当然今后使用RecycleView会是一种趋势,和AS一样,找机会要研究一下。

作者:XycZero
查看原文:http://www.xyczero.com/blog/article/18/.

微信朋友圈广告来了

mikel阅读(1211)

不是喊狼来了,真的微信朋友圈广告今天测试中,微信团队发在朋友圈中的一则测试,让媒体圈炸了窝,大家纷纷喊着微信终于不淡定了,要放广告了!看来移动互联网的盈利模式还是广告收入最直接,最暴利,试问如果朋友圈突然多出个推广广告来,你是什么感受?反正我是觉得有点儿不伦不类,毕竟朋友圈对于人们来说是个自己圈子的概念,连发商品的朋友都会拉黑,微信又非要弄出个广告推广来,还真的令人恶心的。

54bef8a8af7f6

从微信6.1中增强了搜索功能,朋友圈、本地餐饮、还有公众号的信息都可以搜到,微信这个APP一下子让百度坐立不安了,那么多的人在用,然后又每天那么多的原创信息,变相的成了微信搜索的数据基础,不用采集,各种人才自发的贡献内容给微信,唯恐自己的内容没有吸引力,都在卯足力劲儿上干货,上原创,微信不用蜘蛛,坐着就把信息采集的工作做了,社交的力量实在是恐怖,不久的将来估计,微信的竞价推广不远了,毕竟公众号已经以后广告位了不是?!

一直嚷嚷着互联网变天了,没想到变得最快的还是腾讯系的,看来BAT的各位要抓紧了。

[转载]编译器错误消息: CS0234: 命名空间“System”中不存在类型或命名空间名称“Linq”(是否缺少程序集引用?) - 雨落水含烟 - 博客园

mikel阅读(1305)

[转载]编译器错误消息: CS0234: 命名空间“System”中不存在类型或命名空间名称“Linq”(是否缺少程序集引用?) – 雨落水含烟 – 博客园.

错误提示:

说明: 在编译向该请求提供服务所需资源的过程中出现错误。请检查下列特定错误详细信息并适当地修改源代码。
编译器错误消息: CS0234: 命名空间“System”中不存在类型或命名空间名称“Linq”(是否缺少程序集引用?)
源错误:

行 3:  using System.Configuration;
行 4:  using System.Data;
行 5:  using System.Linq;
行 6:  using System.Web;
行 7:  using System.Web.Security;
提示信息告诉我们项目中缺少System.Linq引用。当然解决方案就是添加Linq引用。如何添加?
网上的一些解决方案:
1.添加System.data.Linq  System.xml.linq,System.xml,然而有时这个问题就解决了。然而有些用户依然受到该问题的困扰。
我就是后者。
解决方案:添加System.Core(3.5)
反思:
Linq是.net fx3.5 版本以后才出现的。默认在fx2.0是不会有Linq的。所以会出现这种现象。当用vs2008进行web开发时,将
网站的dot net版本设为3.5时,相应的3.5类库并没有加载进来。就会出现缺少引用的问题。
总之将fx3.5的相关类库加载进去即可。
当然如果项目中用不到Linq可以将dot net 版本设为2.0。避免不必要的错误。

[转载]Visual Studio IDE 实用小技巧(附打包下载) - 夏楚枫 - 博客园

mikel阅读(818)

[转载]Visual Studio IDE 实用小技巧(附打包下载) – 夏楚枫 – 博客园.

       看到《Visual Studio 2010 实用功能总结》2篇文章大家都比较喜欢,我也来补充一些Visual Studio的实用小技巧。

 

1、Visual Studio配色方案。

如果你想让你的编辑器换一种风格显示,你可以在工具—〉选项—〉字体和颜色中进行设置,但是最好的方式是下载精选的这6套配色方案

使用方法选择工具—〉导入和导出设置,然后按提示进行着设置。

 

 

2、代码段

按下Ctrl+K+S 或 Ctrl+K+X 键会出现代码段提示。你可以选择需要的代码段按回车生成。或者直接输入代码段的快捷简写按下 TAB两次生成。例如输入:foreach,按两下 TAB会自动生成代码。可以在这里下载C#的官方扩充代码段包。还可以在网上搜索网友编辑的代码段包。http://snippetlibcsharp.codeplex.com/ 是个不错的扩充。当然你可以编辑你自己的代码段。你不需要懂得描述代码段的XML语法。只需要下载这个现成的代码段编辑工具,很高兴它是作为VS的插件提供。更高兴这个工具是开源的。要使用你下载或自己编辑的代码段,解压他们放到 我的文档\Visual Studio 2XXX\Code Snippets\Visual C#目录下。或者在“工具”—〉“代码段管理器”进行导入。(我的IDE工具菜单下没有,只能按Ctrl+k+B了)

3、扩展如果你用的不是VS2010便不能使用 VS2010->Tools->Extension Manager的扩展管理功能。但你同样可以在Visual Studio 库找到1,789个扩展的项目。要想自己开发扩展,关注我的Visual Studio 扩展编程-#0:如何开始!系列文章(刚刚开始写),里面介绍了更多资源。

 

4、其他更多技巧

编辑HTML时的属性值引号自动插入:

 

这里设置自动排版格式,你可以定制缩进、大括号是否默认在方法括号之后,你可以下载我的IDE所有设置方案。然后用工具—〉导入和导出设置导入它。

还有另一种代码段:将任意编辑器中的文本字节选定拖到工具箱,在需要的时候再拖下来。如图:

附:(VS系统通用快捷键:)

1、自动排版(类似VC6中的Alt+F8)
编辑.格式化选定内容 Ctrl + K,Ctrl + F 根据周围的代码行,正确缩进选定的代码行。

2、注释与去掉注释功能。
编辑.注释选定内容 Ctrl + K,Ctrl + C 使用编程语言的正确注释语法将代码的当前行标记为注释。
编辑.取消注释选定内容 Ctrl + K,Ctrl + U 从代码的当前行中移除注释语法。
将插入点移动到文档中的下一个大括号处。
编辑.转到大括号 Ctrl + ] 将插入点移动到文档中的下一个大括号处。
编辑.向下滚动一行 Ctrl + 向下键 将文本向下滚动一行。仅可用于文本编辑器。
编辑.向上滚动一行 Ctrl + 向上键 将文本向上滚动一行。仅可用于文本编辑器。

3.怎么找到解决方案
视图.解决方案资源管理器 Ctrl + Alt + L 显示解决方案资源管理器,它列出当前解决方案中的项目和文件

4.显示“工具箱”
视图.工具箱 Ctrl + Alt + X 显示“工具箱”,其中包含可包括在代码中或与代码一起使用的控件和其他项。

5.清除项目中的所有断点
调试.删除所有断点 Ctrl + Shift + F9 清除项目中的所有断点。

调试.反汇编 Ctrl + Alt + D 显示“反汇编”窗口。
调试.切换断点 F9 在当前行设置或移除断点。
***********************************************
VS2008 快捷键
新建项目 Ctrl+shift+N
新建网站 shift+Alt+N
文件 Ctrl+N
打开项目/解决方案 Ctrl+shift+O
打开网站 shift+Alt+O
打开文件 Ctrl+O
保存当前文件 Ctrl+S
全部保存 Ctrl+Shift+S
添加新项 Ctrl+Shift+A
添加现有项 Shift+Alt+A
添加类 Shift+Alt+C
撤消 Ctrl+Z
重复 Ctrl+Y
转到 Ctrl+G
循环应用剪贴板中的复制项Ctrl+Shift+V
设置文档的格式 Ctrl+E,D
设置选定内容的格式Ctrl+E,F
转换为大写 Ctrl+Shift+U
转换为小写 Ctrl+U
删除水平空白Ctrl+E,\
查看空白Ctrl+E,S
自动换行Ctrl+E,W
渐进式搜索Ctrl+I
注释选定内容Ctrl+E,C
取消注释选定内容Ctrl+E,U
快速查找 Ctrl+F
快速替换 Ctrl+H
在文件中查找 Ctrl+Shift+F
查找下一个 F3
查找上一个 Shift+F3
在文件中替换 Ctrl+Shift+H
查找符号 Alt+F12
切换书签 Ctrl+B,T
启用书签 Ctrl+B,E
上一书签 Ctrl+B,P
下一书签 Ctrl+B,N
清除书签 Ctrl+B,C
添加任务列表快捷方式Ctrl+E,T
切换大纲显示展开Ctrl+M,M
切换所有大纲显示Ctrl+M,L
停止大纲显示 Ctrl+M,P
折叠到定义 Ctrl+M,O
生产方法存根 Ctrl+K,M
列出成员 Ctrl+K,L
参数信息 Ctrl+K,P
快速信息 Ctrl+K,I
完成单词 Ctrl+K,W
插入代码段 Ctrl+K,X
外侧代码 Ctrl+K,S
代码 F7
设计器 Shift+F7
服务器资源管理器 Ctrl+W,L
解决方案资源管理器 Ctrl+W,S
类视图 Ctrl+W,c
代码定义窗口Ctrl+W,D
对象浏览器 Ctrl+W,J
错误列表 Ctrl+W,E
输出 Ctrl+W,O
属性窗口 Ctrl+W,P
任务列表 Ctrl+W,T
工具箱 Ctrl+W,X
全屏显示shift+Alt+Enter
向后定位 Ctrl+-
向前定位 Ctrl+Shift+-
属性页 Shift+F4
查找符号结果 Ctrl+W,Q
书签窗口 Ctrl+W,B
命令窗口 Ctrl+W,A
文档大纲 Ctrl+W,U
资源视图 Ctrl+W,R
宏资源管理器 Alt+F8
Web浏览器 Ctrl+W,W
重命名 F2
提取方法 Ctrl+R,M
封装字段 Ctrl+R,E
提取接口 Ctrl+R,I
将局部变量提升为参数 Ctrl+R,P
移除参数 Ctrl+R,V
重新排列参数 Ctrl+R,O
生成解决方案 F6
生成当前项目 Shift+F6
启动调试 F5
继续 F5
全部中断 Ctrl+Alt+Break
停止调试 Shift+F5
重新启动 Ctrl+Shift+F5
开始执行(不调试)Ctrl+F5
异常 Ctrl+D,E
逐语句 F11
跳出 Shift+F11
逐过程 F10
切换断点 F9
删除所有断点 Ctrl+Shift+F9
断点 Ctrl+D,B
即时 Ctrl+D,I
快速监视 Ctrl+D,Q
监视1 Ctrl+D,W
监视2 Ctrl+D+W,2
监视3 Ctrl+D+W,3
监视4 Ctrl+D+W,4
自动窗口Ctrl+D,A
局部变量 Ctrl+D,L
调用堆栈 Ctrl+D,C
线程 Ctrl+D,T
切换当前线程标志状态 Ctrl+8
仅显示标志的线程 Ctrl+9
模块 Ctrl+D,M
进程 Ctrl+D,P
反编译 Ctrl+Alt+D
寄存器 Ctrl+D,R
内存1 Ctrl+D,Y
内存2 Ctrl+Alt+M,2
内存3 Ctrl+Alt+M,3
内存4 Ctrl+Alt+M,4
附加到进程 Ctrl+Alt+P
代码段管理器 Ctrl+K,Ctrl+B
运行当前宏 Ctrl+Shift+P
记录当前宏 Ctrl+Shift+R
宏IDE Alt+F11
当前上下文中的测试 Ctrl+R,T
解决方案中的所有测试Ctrl+R,A
如何实现 Ctrl+F1,H
搜索 Ctrl+F1,S
目录 Ctrl+F1,C
索引 Ctrl+F1,I
帮助收藏夹 Ctrl+F1,F
动态帮助 Ctrl+F1,D
索引结果 Ctrl+F1,T

 

[转载]VS2010配色方案 - 天才小强.SunQ 的专栏 - 博客频道 - CSDN.NET

mikel阅读(928)

[转载]VS2010配色方案 – 天才小强.SunQ 的专栏 – 博客频道 – CSDN.NET.

 http://studiostyles.info

这个网站专门为vs 2005, vs 2008, vs2010提供配色方案下载。

网站首页罗列出大量的配色方案,都附有缩略图以及rated(评估),dls(下载数),views(浏览数)。

可以方便的找到优秀的配色方案。当然,自己喜欢的才是最优秀的。

配置方法:

  进入喜欢的方案后,如决定要下载,注意选择自己的vs版本。

  下载的是一个vssettings文件。

  导入步骤:  工具————导入和导出设置————导入选定的环境设置————否,仅导入新设置————然后“浏览”选刚

  刚下载的vssetings文件————完成。

  打开代码,看看理不理想。不理想就再换。

  注意:有的时候配色方案不会立刻全部生效。  没事,重启下vs。

做技术的和玩营销的

mikel阅读(1017)

源码是互联网上难得的资源,同样这部分资源目前开源得不说,就说那些知名的网站源码,基本都加密并且公开在卖,这就是互联网上做技术的,卖源码同时卖服务赚钱的模式,可以说技术在手,赚钱无忧;

另外一帮人是玩营销的,那就是那些把握着很多源码资源,但是不懂技术的人们,他们在淘宝、站长、网赚站上兜售着各种源码资源,至于这些源码资源是从何而来,那就不得而知了,反正就一个便宜,便宜到自己都觉得震惊的地步,几元钱一个网站源码,10分钟建站,我了个去,这就是玩儿营销的,倒手就在赚钱;

这些玩营销的让那些做技术的头疼,自己辛辛苦苦写得系统,被人家倒手变成商品卖了,骂营销的不道德的同时,也就只有骂了,于是各种加密、限制技术手段全用上防止被盗,可是依然难逃被卖的命运,后来一部分做技术的弄明白了,那就卖服务吧,你们倒腾源码的不懂技术,不懂服务,你卖得越多,服务跟不上,照样还得找官方的技术支持来服务,这样就干脆吧源码开源了,大家免费用,我提供技术支持赚钱就ok了,不再苦逼的赚更苦逼的屌丝的钱,只赚高大上的大客户的钱,轻松多了,只需要服务好几家大客户就行了,节约人力成本,还提高了服务质量,这就是自己革了自己的命。

这下玩营销的没得玩儿了,别低估了人们的头脑,你不是开源了吗,玩营销的雇了一帮做技术的给把开源的系统改了,改得更接地气儿了,因为玩营销的天天和客户打交道,知道客户的真实需求,没用的不要了,有用的加上,一下子高大上了,也开始标价卖了!也把自己的命给革了,活得挺好。

这就是市场下的变革,谁都会找到活法儿,谁也不能等死。

QQ截图20140626224042

[转载]ASP.NET MVC 3 | The ASP.NET Site

mikel阅读(756)

[转载]ASP.NET MVC 3 | The ASP.NET Site.

Overview

This document describes the release of ASP.NET MVC 3 RTM for Visual Studio 2010. ASP.NET MVC is a framework for developing Web applications that uses the Model-View-Controller (MVC) pattern. The ASP.NET MVC 3 installer includes the following components:

  • ASP.NET MVC 3 runtime components
  • ASP.NET MVC 3 Visual Studio 2010 tools
  • ASP.NET Web Pages run-time components
  • ASP.NET Web Pages Visual Studio 2010 tools
  • Microsoft Package Manager for .NET (NuGet)
  • An update for Visual Studio 2010 that enables support for Razor syntax. (For details, see KnowledgeBase article 2483190.)

The full set of release notes for each pre-release version of ASP.NET MVC 3 can be found on the ASP.NET website at the following URL:

http://www.asp.net/learn/whitepapers/mvc3-release-notes

Installation Notes

To install ASP.NET MVC 3 RTM using the Web Platform Installer (Web PI), visit the following page:

http://www.microsoft.com/web/gallery/install.aspx?appid=MVC3

Alternatively, you can download the installer for ASP.NET MVC 3 RTM for Visual Studio 2010 from the following page:

http://go.microsoft.com/fwlink/?LinkID=208140

ASP.NET MVC 3 can be installed and can run side-by-side with ASP.NET MVC 2.

Software Requirements

The ASP.NET MVC 3 run-time components require the following software:

  • .NET Framework version 4.ASP.NET MVC 3 Visual Studio 2010 tools require the following software:
  • Visual Studio 2010 or Visual Web Developer 2010 Express.

    Documentation

    Documentation for ASP.NET MVC is available on the MSDN Web site at the following URL:

    http://go.microsoft.com/fwlink/?LinkId=205717

    Tutorials and other information about ASP.NET MVC are available on the MVC page of the ASP.NET Web site at the following URL:

    http://www.asp.net/mvc/

    Support

    This is a fully supported release. Information about getting technical support can be found at the Microsoft Support website.

    Also feel free to post questions about this release to the ASP.NET MVC forum, where members of the ASP.NET community are frequently able to provide informal support:

    http://forums.asp.net/1146.aspx

    Upgrading an ASP.NET MVC 2 Project to ASP.NET MVC 3 Tools Update

    ASP.NET MVC 3 can be installed side by side with ASP.NET MVC 2 on the same computer, which gives you flexibility in choosing when to upgrade an ASP.NET MVC 2 application to ASP.NET MVC 3.

    To manually upgrade an existing ASP.NET MVC 2 application to version 3, do the following:

    1. Create a new empty ASP.NET MVC 3 project on your computer. This project will contain some files that are required for the upgrade.
    2. Copy the following files from the ASP.NET MVC 3 project into the corresponding location of your ASP.NET MVC 2 project. You’ll need to update any references to the JQuery library to account for the new filename ( JQuery-1.5.1.js):
      • /Views/Web.config
      • /packages.config
      • /scripts/*.js
      • /Content/themes/*.*
    3. Copy the packages folder in the root of the empty ASP.NET MVC 3 project solution into the root of your solution, which is in the directory where the solution’s .sln file is located.
    4. If your ASP.NET MVC 2 project contains any areas, copy the /Views/Web.config file to the Views folder of each area.
    5. In both Web.config files in the ASP.NET MVC 2 project, globally search and replace the ASP.NET MVC version. Find the following:
      System.Web.Mvc, Version=2.0.0.0

      Replace it with the following:

      System.Web.Mvc, Version=3.0.0.0
    6. In Solution Explorer, delete the reference to System.Web.Mvc (which points to the DLL from version 2), then add a reference to System.Web.Mvc (v3.0.0.0).
    7. Add a reference to System.Web.WebPages.dll andSystem.Web.Helpers.dll. These assemblies are located in the following folders:
      • %ProgramFiles%\ Microsoft ASP.NET\ASP.NET MVC 3\Assemblies
      • %ProgramFiles%\ Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies
    8. In Solution Explorer, right-click the project name and select Unload Project. Then right-click the project name again and select Edit ProjectName.csproj.
    9. Locate the ProjectTypeGuids element and replace {F85E285D-A4E0-4152-9332-AB1D724D3325} with {E53F8FEA-EAE0-44A6-8774-FFD645390401}.
    10. Save the changes, right-click the project, and then select Reload Project.
    11. In the application’s root Web.config file, add the following settings to the assemblies section.
      <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, 
           PublicKeyToken=31BF3856AD364E35" />
      
      <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral,
           PublicKeyToken=31BF3856AD364E35" />
    12. If the project references any third-party libraries that are compiled using ASP.NET MVC 2, add the following highlighted bindingRedirect element to the Web.config file in the application root under the configuration section:
      <runtime>
         <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
           <dependentAssembly>
             <assemblyIdentity name="System.Web.Mvc"
                 publicKeyToken="31bf3856ad364e35"/>
             <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0"/>
           </dependentAssembly>
         </assemblyBinding>
      </runtime>

    Changes in ASP.NET MVC 3 Tools Update

    This section describes changes made in the ASP.NET MVC 3 Tools Update release since the ASP.NET MVC 3 RTM release.

    “Add Controller” dialog box can now scaffold controllers with views and data access code

    Scaffolding is a way of quickly generating a controller and views for your application. After the code has been generated, you can edit it to meet your project’s requirements.

    To launch the Add Controller dialog box in ASP.NET MVC 3, right-click the Controllers folder in Solution Explorer, click Add, and then click Controller. The dialog box has been enhanced to offer additional scaffolding options.

    There are three scaffolding templates available by default.

    Empty Controller

    This template generates an empty controller file. This template is equivalent to not checking Add actions for create, edit, details, delete scenarios in previous versions of ASP.NET MVC. If you choose this, no further options are available.

    Controller with empty read/write actions

    This template generates a controller file that has all the required action methods but no implementation code in the methods. This template is equivalent to checking Add actions for create, edit, details, delete scenarios in previous versions of ASP.NET MVC. If you choose this, no further options are available.

    Controller with read/write actions and views, using Entity Framework

    This template enables you to quickly create a working data-entry user interface. It generates code that handles a range of common requirements and scenarios, such as the following:

    • Data access. The generated code reads and writes entities in a database. It works with the Entity Framework Code First approach if you choose an existing data context class or if you let the template generate a new DbContext class. It also works with the Entity Framework Database First or Model First approach if you choose an existing ObjectContext class.
    • Validation. The generated code uses ASP.NET MVC model binding and metadata features so that form submissions are validated according to rules declared on your model class. This includes built-in validation rules, such as the Required and StringLength attributes, and custom validation rules.
    • One-to-many relationships. If you define one-to-many foreign-key relationships between your model classes, the generated code will produce drop-down lists for selecting related entities. For example, you might define the following model classes following Entity Framework Code First conventions:
      public class Product
      {
           public int ProductId { get; set; }
           [Required]
           public string Name { get; set; }
      
           // Product belongs to Category
           public int CategoryId { get; set; }
           public virtual Category Category { get; set; }
      }
      public class Category
      {
           public int CategoryId { get; set; }
           [Required]
           public string Name { get; set; }
      }

      When you then scaffold a controller for the Product class, its views will allow users to choose a Category object for each Product instance.

      This template enables additional options in the Add Controller dialog box. For Model class, you can choose any model class in your solution, which determines the type of data that users will be able to create or edit:

    • If you want to use Entity Framework Code First, you can choose any model class.
    • If you are using Entity Framework Database First or Entity Framework Model First, be sure to choose an entity class defined in your conceptual model.

    For Data Context class, you can make these choices:

    • If you want to use Code First and have no existing data context class, choose <New data context…>”. A data context class will then be generated for you.
    • If you want to use Code First and have an existing data context class, choose it here. It will be updated to persist the model class you have selected.
    • If you are using Database First or Model First, choose your object context class here.

    For Views, choose the view engine you want to use, or choose None if you don’t want to scaffold any views.

    You can select Advanced Options to specify further options for the generated views. For example, you can choose the layout or master page to use.

    Improvements to the “ASP.NET MVC 3 New Project” Dialog Box

    The dialog box you use to create new ASP.NET MVC 3 projects includes multiple improvements, as listed below.

    New “Intranet Project” Template

    The Project Template list includes a new Intranet Application template. This template contains settings for building a web application using Windows authentication instead of forms authentication. Because an intranet application requires some IIS settings that can’t be encapsulated in a project template, the template includes a readme file with instructions for how to make the project template work in IIS. Documentation for the a new Intranet Application template is available on the MSDN website at the following URL:

    http://msdn.microsoft.com/en-us/library/gg703322(VS.98).aspx

    Project templates are now HTML5 enabled

    The new-project dialog box now contains an option to add HTML5-specific features to the project templates. Selecting the option causes views to be generated that contain the new HTML5 <header>, <footer>, and <navigation> elements.

    Note that earlier versions of browsers do not support HTML5-specific tags. To address this limitation, the HTML5 project templates include a reference to the Modernizr library. (See the next section.)

    Project templates now include Modernizr 1.7

    Modernizr is a JavaScript library that enables support for CSS 3 and HTML5 in browsers that do not yet support these features. This library is included as a pre-installed NuGet package in templates for ASP.NET MVC 3 projects. For more information about Modernizr, see http://www.modernizr.com/.

    Project templates include updated versions of JQuery, jQuery UI, and jQuery Validation

    The project templates now include the following versions of the jQuery scripts:

    • jQuery 1.5.1
    • jQuery Validation 1.8
    • jQuery UI 1.8.11

    These libraries are included as pre-installed NuGet packages.

    Project templates now include ADO.NET Entity Framework 4.1 as a pre-installed NuGet package

    The ADO.NET Entity Framework 4.1 includes the Code First feature. Code First is a new development pattern for the ADO.NET Entity Framework that provides an alternative to the existing Database First and Model First patterns.

    Code First is focused around defining your model using POCO classes (“plain old CLR objects”) written in Visual Basic or C#. These classes can then be mapped to an existing database or be used to generate a database schema. Additional configuration can be supplied using DataAnnotations attributes or using fluent APIs.

    Documentation for using Code First with ASP.NET MVC is available on the ASP.NET website at the following URLs:

    http://www.asp.net/mvc/tutorials/getting-started-with-mvc3-part1-cs http://www.asp.net/entity-framework/tutorials/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

    Project templates include JavaScript libraries as pre-installed NuGet packages

    When you create a new ASP.NET MVC 3 project, the project includes the JavaScript files mentioned previously (for example, the Modernizr library) by installing them using NuGet instead of directly adding the scripts to the Scripts folder in the project template contents. This enables you to use NuGet to update the scripts to the latest version when new versions of the scripts are released.

    For example, given the frequency of new jQuery releases, the version of jQuery included in the project template will at some point be out of date. However, because jQuery is included as an installed NuGet package, you will be notified in the NuGet dialog box when newer versions of jQuery are available.

    Because jQuery includes the version number in the file name, updating jQuery to the latest version also requires updating the <script> tag that references the jQuery file to use the new file name. Other included script libraries do not include the version number in the script name, so they can be more easily updated to their latest versions.

    Known Issues

    • In some cases, installation may fail with the error message “Installation failed with error code (0x80070643)”. For information about how to work around this issue, see KnowledgeBase article 2531566.
    • The scaffolding for adding a controller does not scaffold entities that take advantage of entity inheritance support within Entity Framework. For example, given a base Person class that’s inherited by a Student class, scaffolding the Student class will result in generated code that does not compile.
    • Creating a new ASP.NET MVC 3 project within a solution folder causes a NullReferenceException error. The workaround is to create the ASP.NET MVC 3 project in the root of the solution and then move it into the solution folder.
    • IntelliSense for Razor syntax does not work when ReSharper is installed. If you have ReSharper installed and want to take advantage of the Razor IntelliSense support in ASP.NET MVC 3, see the entry Razor Intellisense and ReSharper on Hadi Hariri’s blog, which discusses ways to use them together today.
    • During installation, the EULA acceptance dialog box displays the license terms in a window that is smaller than intended.
    • When you are editing a Razor view (.cshtml or .vbhtml file), views. ASP.NET MVC 3 does not include any snippets for Razor views..aspxselecting a code snippet for ASP.NET MVC will show snippets for
    • If you install ASP.NET MVC 3 for Visual Web Developer Express on a computer where Visual Studio is not installed, and then later install Visual Studio, you must reinstall ASP.NET MVC 3. Visual Studio and Visual Web Developer Express share components that are upgraded by the ASP.NET MVC 3 installer. The same issue applies if you install ASP.NET MVC 3 for Visual Studio on a computer that does not have Visual Web Developer Express and then later install Visual Web Developer Express.

    Changes in ASP.NET MVC 3 RTM

    This section describes changes and bug fixes made in the ASP.NET MVC 3 RTM release since the RC2 release.

    Change: Updated the version of jQuery UI to 1.8.7

    The ASP.NET MVC project templates for Visual Studio were updated to include the latest version of the jQuery UI library. The templates also include the minimal set of resource files required by jQuery UI, such as the associated CSS and image files.

    Change: Changed the default ModelMetadataProvider back to DataAnnotationsModelMetadataProvider

    The RC2 release of ASP.NET MVC 3 introduced a CachedDataAnnotationsMetadataProvider class that provided caching on top of the existing DataAnnotationsModelMetadataProvider class as a performance improvement. However, some bugs were reported with this implementation, so the change has been reverted and moved into the MVC Futures project, which is available on the CodePlex website at http://aspnet.codeplex.com/.

    Fixed: Pasting part of a Razor expression that contains whitespace results in it being reversed

    In pre-release versions of ASP.NET MVC 3, when you paste a part of a Razor expression that contains whitespace into a Razor file, the resulting expression is reversed. For example, consider the following Razor code block:

    @SomeMethod("first param",
    100)
    @AnotherMethod()

    If you select the text “first param” in the first method and paste it as an argument into the second method, the result is as follows:

    @AnotherMethod(param""first)

    The correct behavior is that the paste operation should result in the following:

    @AnotherMethod("first param")

    This issue has been fixed in the RTM release so that the expression is correctly preserved during the paste operation.

    Fixed: Renaming a Razor file that is opened in the editor disables syntax colorization and IntelliSense

    Renaming a Razor file using Solution Explorer while the file is opened in the editor window causes syntax highlighting and IntelliSense to stop working for that file. This has been fixed so that highlighting and IntelliSense are maintained after a rename.

    Known Issues

    • If you close Visual Studio 2010 SP1 Beta while the NuGet Package Manager Console is open, Visual Studio crashes and attempts to restart. This will be fixed in the RTM release of Visual Studio 2010 SP1.
    • The ASP.NET MVC 3 installer is only able to install an initial version of the NuGet package manager. After you have installed the initial version, NuGet can be installed and updated using Visual Studio Extension Manager. If you already have NuGet installed, go to the Visual Studio Extension Gallery to update to the latest version of NuGet.
    • Creating a new ASP.NET MVC 3 project within a solution folder causes a NullReferenceException error. The workaround is to create the ASP.NET MVC 3 project in the root of the solution and then move it into the solution folder.
    • The installer might take much longer than previous versions of ASP.NET MVC to complete. This is because it updates components of Visual Studio 2010.
    • IntelliSense for Razor syntax does not work when ReSharper is installed. If you have ReSharper installed and want to take advantage of the Razor IntelliSense support in ASP.NET MVC 3, see the entry Razor Intellisense and ReSharper on Hadi Hariri’s blog, which discusses ways to use them together today.
    • CCSHTML and VBHTML views created with the Beta version of ASP.NET MVC 3 do not have their build action set correctly, with the result that these view types are omitted when the project is published. The Build Action value for these files should be set to “Content”. ASP.NET MVC 3 RTM fixes this issue for new files, but doesn’t correct the setting for existing files for a project created with prerelease versions.
    • During installation, the EULA acceptance dialog box displays the license terms in a window that is smaller than intended./li>
    • When you are editing a Razor view (.cshtml file), the Go To Controller menu item in Visual Studio will not be available, and there are no code snippets.
    • If you install ASP.NET MVC 3 for Visual Web Developer Express on a computer where Visual Studio is not installed, and then later install Visual Studio, you must reinstall ASP.NET MVC 3. Visual Studio and Visual Web Developer Express share components that are upgraded by the ASP.NET MVC 3 installer. The same issue applies if you install ASP.NET MVC 3 for Visual Studio on a computer that does not have Visual Web Developer Express and then later install Visual Web Developer Express.

    Breaking Changes

    • In previous versions of ASP.NET MVC, action filters are create per request except in a few cases. This behavior was never a guaranteed behavior but merely an implementation detail and the contract for filters was to consider them stateless. In ASP.NET MVC 3, filters are cached more aggressively. Therefore, any custom action filters which improperly store instance state might be broken.
    • The order of execution for exception filters has changed for exception filters that have the same Order value. In ASP.NET MVC 2 and earlier, exception filters on the controller that have the same Order value as those on an action method are executed before the exception filters on the action method. This would typically be the case when exception filters are applied without a specified Order value. In ASP.NET MVC 3, this order has been reversed so that the most specific exception handler executes first. As in earlier versions, if the Order property is explicitly specified, the filters are run in the specified order.
    • A new property named FileExtensions was added to the VirtualPathProviderViewEngine base class. When ASP.NET looks up a view by path (not by name), only views with a file extension contained in the list specified by this new property are considered. This is a breaking change in applications where a custom build provider is registered in order to enable a custom file extension for Web Form views and where the provider references those views by using a full path rather than a name. The workaround is to modify the value of the FileExtensions property to include the custom file extension.
    • Custom controller factory implementations that directly implement the IControllerFactory interface must provide an implementation of the new GetControllerSessionBehavior method that was added to the interface in this release. In general, it is recommended that you do not implement this interface directly and instead derive your class from DefaultControllerFactory.

    Changes in ASP.NET MVC 3 RC2

    This section describes changes (new features and bug fixes) made in the ASP.NET MVC 3 RC2 release since the RC release.

    Project Templates Changed to Include jQuery 1.4.4, jQuery Validation 1.7, and jQuery UI 1.8.6

    The project templates for ASP.NET MVC 3 now include the latest versions of jQuery, jQuery Validation, and jQuery UI. jQuery UI is a new addition to the project templates and provides useful user interface widgets. For more information about jQuery UI, visit their homepage: http://jqueryui.com/.

    Added “AdditionalMetadataAttribute” Class

    You can use the AdditionalMetadataAttribute class to populate the ModelMetadata.AdditionalValues dictionary for a model property.

    For example, suppose a view model has properties that should be displayed only to an administrator. That model can be annotated with the new attribute using AdminOnly as the key and true as the value, as in the following example:

    public class ProductViewModel {
      [AdditionalMetadata("AdminOnly", true)]
      public string RefundCode {get; set;}
    }

    This metadata is made available to any display or editor template when a product view model is rendered. It is up to you as application developer to interpret the metadata information.

    Improved View Scaffolding

    The T4 templates used for scaffolding views now generate calls to template helper methods such as EditorFor instead of helpers such as TextBoxFor. This change improves support for metadata on the model in the form of data annotation attributes when the Add View dialog box generates a view.

    The Add View scaffolding also includes improved detection and usage of primary key information on the model, based on convention. For example, the Add View dialog box uses this information to ensure that the primary key value is not scaffolded as an editable form field.

    The default Edit and Create templates include references to the jQuery scripts needed for client validation.

    Added Html.Raw Method

    By default, the Razor view engine HTML-encodes all values. For example, the following code snippet encodes the HTML inside the greeting variable so that it is displayed in the page as &lt;strong&gt;Hello World!&lt;/strong&gt;.

    @{
      string greeting = "<strong>Hello World!</strong>";
    }
    
    <p>@greeting</p>

    The new Html.Raw method provides a simple way of displaying unencoded HTML when the content is known to be safe. The following example displays the same string, but the string is rendered as markup:

    @{
      string greeting = "<strong>Hello World!</strong>";
    }
    
    <p>@Html.Raw(greeting)</p>

    Renamed “Controller.ViewModel” Property and the “View” Property To “ViewBag”

    Previously, the ViewModel property of Controller corresponded to the View property of a view. Both of these properties provide a way to access values of the ViewDataDictionary object using dynamic property-accessor syntax. Both properties have been renamed to be the same in order to avoid confusion and to be more consistent.

    Renamed “ControllerSessionStateAttribute” Class to “SessionStateAttribute”

    The ControllerSessionStateAttribute class was introduced in the RC release of ASP.NET MVC 3. The property was renamed to be more succinct.

    Renamed RemoteAttribute “Fields” Property to “AdditionalFields”

    The RemoteAttribute class’s Fields property caused some confusion among users. Renaming this property to AdditionalFields clarifies its intent.

    Renamed “SkipRequestValidationAttribute” to “AllowHtmlAttribute”

    The SkipRequestValidationAttribute attribute was renamed to AllowHtmlAttribute to better represent its intended usage.

    Changed “Html.ValidationMessage” Method to Display the First Useful Error Message

    The Html.ValidationMessage method was fixed to show the first useful error message instead of simply displaying the first error.

    During model binding, the ModelState dictionary can be populated from multiple sources with error messages about the property, including from the model itself (if it implements IValidatableObject), from validation attributes applied to the property, and from exceptions thrown while the property is being accessed.

    When the Html.ValidationMessage method displays a validation message, it skips model-state entries that include an exception, because these are generally not intended for the end user. Instead, the method looks for the first validation message that is not associated with an exception and displays that message. If no such message is found, it defaults to a generic error message that is associated with the first exception.

    Fixed @model Declaration to not Add Whitespace to the Document

    In earlier releases, the @model declaration at the top of a view added a blank line to the rendered HTML output. This has been fixed so that the declaration does not introduce whitespace.

    Added “FileExtensions” Property to View Engines to Support Engine-Specific File Names

    A view engine can return a view using an explicit view path as in the following example:

    return View("~/views/home/index.cshtml");

    The first view engine always attempts to render the view. By default, the Web Forms view engine is the first view engine; because the Web Forms engine cannot render a Razor view, an error occurs. View engines now have a FileExtensions property that is used to specify which file extensions they support. This property is checked when ASP.NET determines whether a view engine can render a file. This is a breaking change and more details are included in the Breaking Changes section of this document.

    Fixed “LabelFor” Helper to Emit the Correct Value for the “For” Attribute

    A bug was fixed where the LabelFor method rendered a for attribute that matches the input element’s name attribute instead of its ID. According to the W3C, the for attribute should match the input element’s ID.

    Fixed “RenderAction” Method to Give Explicit Values Precedence During Model Binding

    In earlier versions, explicit values that were passed to the RenderAction method were being ignored in favor of the current form values during model binding inside a child action. The fix ensures that explicit values take precedence during model binding.

    Breaking Changes

    • In previous versions of ASP.NET MVC, action filters were created per request except in a few cases. This behavior was never a guaranteed behavior but merely an implementation detail and the contract for filters was to consider them stateless. In ASP.NET MVC 3, filters are cached more aggressively. Therefore, any custom action filters which improperly store instance state might be broken.
    • The order of execution for exception filters has changed for exception filters that have the same Order value. In ASP.NET MVC 2 and earlier, exception filters on the controller that had the same Order value as those on an action method were executed before the exception filters on the action method. This would typically be the case when exception filters were applied without a specified Order value. In ASP.NET MVC 3, this order has been reversed so that the most specific exception handler executes first. As in earlier versions, if the Order property is explicitly specified, the filters are run in the specified order.
    • A new property named FileExtensions was added to the VirtualPathProviderViewEngine base class. When ASP.NET looks up a view by path (not by name), only views with a file extension contained in the list specified by this new property are considered. This is a breaking change in applications where a custom build provider is registered in order to enable a custom file extension for Web Form views and where the provider references those views by using a full path rather than a name. The workaround is to modify the value of the FileExtensions property to include the custom file extension.
    • Custom controller factory implementations that directly implement the IControllerFactory interface must provide an implementation of the new GetControllerSessionBehavior method that was added to the interface in this release. In general, it is recommended that you do not implement this interface directly and instead derive your class from DefaultControllerFactory.

    Known Issues

    • The ASP.NET MVC 3 installer is only able to install an initial version of the NuGet package manager. After you have installed the initial version, NuGet can be installed and updated using Visual Studio Extension Manager. If you already have NuGet installed, go to the Visual Studio Extension Gallery to update to the latest version of NuGet.
    • Creating a new ASP.NET MVC 3 project within a solution folder causes a NullReferenceException error. The workaround is to create the ASP.NET MVC 3 project in the root of the solution and then move it into the solution folder.
    • The installer might take much longer than previous versions of ASP.NET MVC to complete. This is because it updates components of Visual Studio 2010.
    • IntelliSense for Razor syntax does not work when ReSharper is installed. If you have ReSharper installed and want to take advantage of the Razor IntelliSense support in ASP.NET MVC 3 RC2, see the entry Razor Intellisense and ReSharper on Hadi Hariri’s blog, which discusses ways to use them together today.
    • CSHTML and VBHTML views created with the Beta version of ASP.NET MVC 3 do not have their build action set correctly, with the result that these view types are omitted when the project is published. The Build Action value for these files should be set to Content”. ASP.NET MVC 3 RC2 fixes this issue for new files, but doesn’t correct the setting for existing files for a project created with the Beta version.
    • During installation, the EULA acceptance dialog box displays the license terms in a window that is smaller than intended.
    • When you are editing a Razor view (.cshtml file), the Go To Controller menu item in Visual Studio will not be available, and there are no code snippets.
    • If you install ASP.NET MVC 3 for Visual Web Developer Express on a computer where Visual Studio is not installed, and then later install Visual Studio, you must reinstall ASP.NET MVC 3. Visual Studio and Visual Web Developer Express share components that are upgraded by the ASP.NET MVC 3 installer. The same issue applies if you install ASP.NET MVC 3 for Visual Studio on a computer that does not have Visual Web Developer Express and then later install Visual Web Developer Express.
    • Installing ASP.NET MVC 3 RC 2 does not update NuGet if you already have it installed. To upgrade NuGet, go to the Visual Studio Extension manager and it should show up as an available update. You can upgrade NuGet to the latest release from there.

    ASP.NET MVC 3 Release Candidate

    ASP.NET MVC Release Candidate was released on November 9, 2010.

    New Features in ASP.NET MVC 3 RC

    This section describes features that have been introduced in the ASP.NET MVC 3 RC release since the Beta release.

    NuGet Package Manager

    ASP.NET MVC 3 includes the NuGet Package Manager (formerly known as NuPack), which is an integrated package management tool for adding libraries and tools to Visual Studio projects. This tool automates the steps that developers take today to get a library into their source tree.

    You can work with NuGet as a command-line tool, as an integrated console window inside Visual Studio 2010, from the Visual Studio context menu, and as a set of PowerShell cmdlets.

    For more information about NuGet, visit http://NuGet.codeplex.com/ and read the Getting Started Guide.

    Improved “New Project” Dialog Box

    When you create a new project, the New Project dialog box now lets you specify the view engine as well as an ASP.NET MVC project type.

    Support for modifying the list of templates and view engines listed in the dialog box is included in this release.

    The default templates are the following:

    Empty. Contains a minimal set of files for an ASP.NET MVC project, including the default directory structure for ASP.NET MVC projects, a Site.css file that contains the default ASP.NET MVC styles, and a Scripts directory that contains the default JavaScript files.

    Internet Application. Contains sample functionality that demonstrates how to use the membership provider with ASP.NET MVC.

    The list of project templates that is displayed in the dialog box is specified in the Windows registry.

    Sessionless Controllers

    The new ControllerSessionStateAttribute gives you more control over session-state behavior for controllers by specifying a System.Web.SessionState.SessionStateBehavior enumeration value.

    The following example shows how to turn off session state for all requests to a controller.

    [ControllerSessionState(SessionStateBehavior.Disabled)]
    public class CoolController : Controller {
      public ActionResult Index() {
        object o = Session["Key"]; // Causes an exception.
    
      }
    }

    The following example shows how to set read-only session state for all requests to a controller.

    [ControllerSessionState(SessionStateBehavior.ReadOnly)]
    public class CoolController : Controller {
      public ActionResult Index() {
        Session["Key"] = "value"; // Value is not available in
    the next request
      }
    }

    New Validation Attributes

    CompareAttribute

    The new CompareAttribute validation attribute lets you compare the values of two different properties of a model. In the following example, the ComparePassword property must match the Password field in order to be valid.

    public class User {
        [Required]
    
        public string Password { get; set; }
        [Required, Compare("Password")]
        public string ComparePassword { get; set; }
    }

    RemoteAttribute

    The new RemoteAttribute validation attribute takes advantage of the jQuery Validation plug-in’s remote validator, which enables client-side validation to call a method on the server that performs the actual validation logic.

    In the following example, the UserName property has the RemoteAttribute applied. When editing this property in an Edit view, client validation will call an action named UserNameAvailable on the UsersController class in order to validate this field.

    public class User {
        [Remote("UserNameAvailable", "Users")]
        public string UserName { get; set; }
    }

    The following example shows the corresponding controller.

    public class UsersController {
        public bool UserNameAvailable(string username) {
            if(MyRepository.UserNameExists(username)) {
                return "false";
            }
            return "true";
        }
    }

    By default, the property name that the attribute is applied to is sent to the action method as a query-string parameter.

    New Overloads for “LabelFor” and “LabelForModel” Methods

    New overloads have been added for the LabelFor and LabelForModel methods that let you specify the label text. The following example shows how to use these overloads.

    @Html.LabelFor(m => m.PropertyName,
    "Label Text");
    @Html.LabelForModel("Label Text");

    Child Action Output Caching

    The OutputCacheAttribute supports output caching of child actions that are called by using the Html.RenderAction or Html.Action helper methods. The following example shows a view that calls another action.

    Hi there. The uncached time is:
    @DateTime.Now
    The cached time is: @Html.Action("GetDate")

    The GetDate action is annotated with the OutputCacheAttribute:

    [OutputCache(Duration = 100,
    VaryByParam = "none")]
    public string GetDate() {
        return DateTime.Now.ToString();
    }

    When this code runs, the result of the call to Html.Action(“GetDate”) is cached for 100 seconds.

    “Add View” Dialog Box Improvements

    When you add a strongly typed view, the Add View dialog box now filters out more non-applicable types than in previous releases, such as many core .NET Framework types. Also, the list is now sorted by the class name and not by the fully qualified type name, which makes it easier to find types. For example, the type name is now displayed as in the following example:

    ClassName (namespace)

    In earlier releases, this would have been displayed as the following:

    Namespace.ClassName

    Granular Request Validation

    The Exclude property of ValidateInputAttribute no longer exists. Instead, to have request validation skipped for specific properties of a model during model binding, use the new SkipRequestValidationAttribute.

    For example, suppose an action method is used to edit a blog post:

    [HttpPost]
    public ActionResult Edit(BlogPostViewModel post) {
        // Save the post in the database
    }

    The following example shows the view model for a blog post.

    public class BlogPostViewModel {
        public int Id {get; set;}
    
        public string Subject {get; set;}
    
        public string Description {get; set;}
    }

    When a user submits some markup for the Description property, model binding will fail due to request validation. To disable request validation during model binding for the blog post Description, apply the SkipRequpestValidationAttribute to the property, as shown in this example:.

    public class BlogPostViewModel {
        public int Id {get; set;}
    
        public string Subject {get; set;}
    
        [SkipRequestValidation]
    
        public string Description {get; set;}
    }

    Alternatively, to turn off request validation for every property of the model, apply ValidateInputAttribute with a value of false to the action method:

    [HttpPost]
    [ValidateInput(false)]
    public ActionResult Edit(BlogPostViewModel post) {
        // Save the post in the database
    }

    Breaking Changes

    • The order of execution for exception filters has changed for exception filters that have the same Order value. In ASP.NET MVC 2 and earlier, exception filters on the controller that had the same Order as those on an action method were executed before the exception filters on the action method. This would typically be the case when exception filters were applied without a specified Order value. In ASP.NET MVC 3, this order has been reversed so that the most specific exception handler executes first. As in earlier versions, if the Order property is explicitly specified, the filters are run in the specified order.
    • Added a new property named FileExtensions to the VirtualPathProviderViewEngine base class. When looking up a view by path (and not by name), only views with a file extension contained in the list specified by this new property is considered. This is a breaking change for those who register a custom build provider to enable a custom file extension for web form views and and are referencing those views by using a full path rather than a name. The workaround is to modify the value of the FileExtensions property to include the custom file extension.

    Known Issues

    • The installer may take much longer than previous versions of ASP.NET MVC to complete because it updates components of Visual Studio 2010.
    • The Add View scaffolding when selecting astrongly typed view scaffolds write-only properties. These should always be ignored by scaffolding. The Add View dialog also scaffolds read-only properties when generating an “Edit” or “Create” view. Read-only properties should only be scaffolded for the Display and List views.
    • Debugging doesn’t work when ASP.NET MVC 3 is installed alongside the Async CTP. ASP.NET MVC 3 cannot be installed side-by-side with the Async CTP. Uninstall the Async CTP to repair Debugging. For more details, read this blog post about uninstalling all the pieces of ASP.NET MVC 3 RC.
    • Razor Intellisense does not work when Resharper is installed. If you have ReSharper installed and want to take advantage of the Razor intellisense support in ASP.NET MVC 3 RC, please read this blog post from JetBrains which discusses ways to use them together today.
    • CSHTML and VBHTML views created with Beta of ASP.NET MVC 3 do not have their build action correctly which omits them from publishing. The Build Action for these files should be set to “Content”. ASP.NET MVC 3 RC fixes this issue for new files, but doesn’t correct the setting for existing files for a project created with the Beta.
    • The installer may take much longer than previous versions of ASP.NET MVC to complete because it updates components of Visual Studio 2010.
    • The Add View scaffolding when selecting an “Edit” strongly typed view scaffolds read only properties. Likewise, write-only properties are scaffolded for “Display” views.
    • During installation, the EULA acceptance dialog box displays the license terms in a window that is smaller than intended.
    • Installing the Visual Studio Async CTP causes a conflict with the Razor release that is included as part of the ASP.NET MVC 3 tooling installation. Make sure that you do not try to install both the Visual Studio Async CTP and the Razor release on the same machine.
    • When you are editing a Razor view (.cshtml file), the Go To Controller menu item in Visual Studio will not be available, and there are no code snippets.

    ASP.NET MVC 3 Beta

    ASP.NET MVC 3 Beta was released on October 6, 2010. The following notes are specific to the Beta release, and are subject to any updates or changes referenced in the ASP.NET MVC 3 Release Candidate section above.

    New Features in ASP.NET MVC 3 Beta

    This section describes features that have been introduced in the ASP.NET MVC 3 Beta release.

    NuPack Package Manager

    ASP.NET MVC 3 includes NuPack Package Manager, which is an integrated package management tool for adding libraries and tools to Visual Studio projects. For the most part, it automates the steps that developers take today to get a library into their source tree.

    You can work with NuPack as a command line tool, as an integrated console window inside Visual Studio 2010, from the Visual Studio context menu, and as set of PowerShell cmdlets.

    For more information about NuPack, visit http://nupack.codeplex.com/ and read the Getting Started Guide.

    Improved New Project Dialog Box

    When you create a new project, the New Project dialog box now lets you specify the view engine as well as an ASP.NET MVC project type.

    Support for modifying the list of templates and view engines listed in the dialog box is not included in this release.

    The default templates are the following:

    Empty. Contains a minimal set of files for an ASP.NET MVC project, including the default directory structure for ASP.NET MVC projects, a small Site.css file that contains the default ASP.NET MVC styles, and a Scripts directory that contains the default JavaScript files.

    Internet Application. Contains sample functionality that demonstrates how to use the membership provider within ASP.NET MVC.

    Simplified Way to Specify Strongly Typed Models in Razor Views

    The way to specify the model type for strongly typed Razor views has been simplified by using the new @model directive for CSHTML views and @ModelType directive for VBHTML views. In earlier versions of ASP.NET MVC, you would specify a strongly typed model for Razor views this way:

      @inherits System.Web.Mvc.WebViewPage

    In this release, you can use the following syntax:

      @model MyModelNamespace.MyModelType

    Support for New ASP.NET Web Pages Helper Methods

    The new ASP.NET Web Pages technology includes a set of helper methods that are useful for adding commonly used functionality to views and controllers. ASP.NET MVC 3 supports using these helper methods within controllers and views (where appropriate). These methods are contained in the System.Web.Helpers assembly. The following table lists a few of the ASP.NET Web Pages helper methods.

    Helper Description
    Chart Renders a chart within a view. Contains methods such as Chart.ToWebImage, Chart.Save, and Chart.Write.
    Crypto Uses hashing algorithms to create properly salted and hashed passwords.
    WebGrid Renders a collection of objects (typically, data from a database) as a grid. Supports paging and sorting.
    WebImage Renders an image.
    WebMail Sends an email message.

    A quick reference topic that lists the helpers and basic syntax is available as part of the ASP.NET Razor syntax documentation at the following URL:

    http://www.asp.net/webmatrix/tutorials/asp-net-web-pages-api-reference

    Additional Dependency Injection Support

    Building on the ASP.NET MVC 3 Preview 1 release, the current release includes added support for two new services and four existing services, and improved support for dependency resolution and the Common Service Locator.

    New IControllerActivator Interface for Fine-Grained Controller Instantiation

    The new IControllerActivator interface provides more fine-grained control over how controllers are instantiated via dependency injection. The following example shows the interface:

    namespace System.Web.Mvc {
        using System.Web.Routing;
    
        public interface IControllerActivator {
            IController Create(RequestContext requestContext, Type controllerType);
        }
    }

    Contrast this to the role of the controller factory. A controller factory is an implementation of the IControllerFactory interface, which is responsible both for locating a controller type and for instantiating an instance of that controller type.

    Controller activators are responsible only for instantiating an instance of a controller type. They do not perform the controller type lookup. After locating a proper controller type, controller factories should delegate to an instance of IControllerActivator to handle the actual instantiation of the controller.

    The DefaultControllerFactory class has a new constructor that accepts an IControllerFactory instance. This lets you apply Dependency Injection to manage this aspect of controller creation without having to override the default controller-type lookup behavior.

    IServiceLocator Interface Replaced with IDependencyResolver

    Based on community feedback, the ASP.NET MVC 3 Beta release has replaced the use of the IServiceLocator interface with a slimmed-down IDependencyResolver interface specific to the needs of ASP.NET MVC. The following example shows the new interface:

    namespace System.Web.Mvc {
        using System.Collections.Generic;
    
        public interface IDependencyResolver {
            object GetService(Type serviceType);
            IEnumerable<object> GetServices(Type serviceType);
        }
    }

    As part of this change, the ServiceLocator class was also replaced with the DependencyResolver class. Registration of a dependency resolver is similar to earlier versions of ASP.NET MVC:

    DependencyResolver.SetResolver(myResolver);

    Implementations of this interface should simply delegate to the underlying dependency injection container to provide the registered service for the requested type.

    When there are no registered services of the requested type, ASP.NET MVC expects implementations of this interface to return null from GetService and to return an empty collection from GetServices.

    The new DependencyResolver class lets you register classes that implement either the new IDependencyResolver interface or the Common Service Locator interface (IServiceLocator). For more information about Common Service Locator, see http://commonservicelocator.codeplex.com/.

    New IViewActivator Interface for Fine-Grained View Page Instantiation

    The new IViewPageActivator interface provides more fine-grained control over how view pages are instantiated via dependency injection. This applies to both WebFormView instances and RazorView instances. The following example shows the new interface:

    namespace System.Web.Mvc {
        public interface IViewPageActivator {
            object Create(ControllerContext controllerContext, Type type);
        }
    }

    These classes now accept an IViewPageActivator constructor argument, which lets you use dependency injection to control how the ViewPage, ViewUserControl, and WebViewPage types are instantiated.

    New Dependency Resolver Support for Existing Services

    The new release includes dependency resolution support for the following services:

    • Model validation providers. Classes that implement ModelValidatorProvider can be registered in the dependency resolver, and the system will use them to support client- and server-side validation.
    • Model metadata provider. A single class that implements ModelMetadataProvider can be registered in the dependency resolver, and the system will use it to provide metadata for the templating and validation systems.
    • Value providers. Classes that implement ValueProviderFactory can be registered in the dependency resolver, and the system will use them to create value providers that are consumed by the controller and during model binding.
    • Model binders. Classes that implement IModelBinderProvider can be registered in the dependency resolver, and the system will use them to create model binders that are consumed by the model binding system.

    New Support for Unobtrusive jQuery-Based Ajax

    ASP.NET MVC includes Ajax helper methods such as the following:

    • Ajax.ActionLink
    • Ajax.RouteLink
    • Ajax.BeginForm
    • Ajax.BeginRouteForm

    These methods use JavaScript to invoke an action method on the server rather than using a full postback. This functionality has been updated to take advantage of jQuery in an unobtrusive manner. Rather than intrusively emitting inline client scripts, these helper methods separate the behavior from the markup by emitting HTML5 attributes using the data-ajax prefix. Behavior is then applied to the markup by referencing the appropriate JavaScript files. Make sure that the following JavaScript files are referenced:

    • jquery-1.4.1.js
    • jquery.unobtrusive.ajax.js

    This feature is enabled by default in the Web.config file in the ASP.NET MVC 3 new project templates, but is disabled by default for existing projects. For more information, see Added application-wide flags for client validation and unobtrusive JavaScript later in this document.

    New Support for Unobtrusive jQuery Validation

    By default, ASP.NET MVC 3 Beta uses jQuery validation in an unobtrusive manner in order to perform client-side validation. To enable unobtrusive client validation, make a call like the following from within a view:

    Html.EnableClientValidation();

    This requires that ViewContext.UnobtrusiveJavaScriptEnabled property is set to true, which you can do by making the following call:

    Html.EnableUnobtrusiveJavaScript();

    Also make sure the following JavaScript files are referenced.

    • jquery-1.4.1.js
    • jquery.validate.js
    • jquery.validate.unobtrusive.js

    This feature is enabled on by default in the Web.config file in the ASP.NET MVC 3 new project templates, but is disabled by default for existing projects. For more information, see New application-wide flags for client validation and unobtrusive JavaScript later in this document.

    New Application-Wide Flags for Client Validation and Unobtrusive JavaScript

    You can enable or disable client validation and unobtrusive JavaScript globally using static members of the HtmlHelper class, as in the following example:

        HtmlHelper.ClientValidationEnabled = true;
        HtmlHelper.UnobtrusiveJavaScriptEnabled = true;

    The default project templates enable unobtrusive JavaScript by default. You can also enable or disable these features in the root Web.config file of your application using the following settings:

        <configuration>
            <appSettings>
                <add key="ClientValidationEnabled" value="true"/>
                <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
            </appSettings>
        </configuration>

    Because you can enable these features by default, new overloads were introduced to the HtmlHelper class that let you override the default settings, as shown in the following examples:

        public void EnableClientValidation();
        public void EnableClientValidation(bool enabled);
        public void EnableUnobtrusiveJavaScript();
        public void EnableUnobtrusiveJavaScript(bool enabled);

    For backward compatibility, both of these features are disabled by default.

    New Support for Code that Runs Before Views Run

    You can now put a file named _viewstart.cshtml (or _viewstart.vbhtml) in the Views directory and add code to it that will be shared among multiple views in that directory and its subdirectories. For example, you might put the following code into the _viewstart.cshtml page in the ~/Views folder:

    @{
        Layout = "~/Views/Shared/_Layout.cshtml";
    }

    This sets the layout page for every view within the Views folder and all its subfolders recursively. When a view is being rendered, the code in the _viewstart.cshtml file runs before the view code runs. The _viewstart.cshtml code applies to every view in that folder.

    By default, the code in the _viewstart.cshtml file also applies to views in any subfolder. However, individual subfolders can have their own version of the _viewstart.cshtml file; in that case, the local version takes precedence. For example, to run code that is common to all views for the HomeController, put a _viewstart.cshtml file in the ~/Views/Home folder.

    New Support for the VBHTML Razor Syntax

    The previous ASP.NET MVC preview included support for views using Razor syntax based on C#. These views use the .cshtml file extension. As part of ongoing work to support Razor, the ASP.NET MVC 3 Beta introduces support for the Razor syntax in Visual Basic, which uses the .vbhtml file extension.

    For an introduction to using Visual Basic syntax in VBHTML pages, see the tutorial at the following URL:

    http://www.asp.net/webmatrix/tutorials/asp-net-web-pages-visual-basic

    More Granular Control over ValidateInputAttribute

    ASP.NET MVC has always included the ValidateInputAttribute class, which invokes the core ASP.NET request validation infrastructure to make sure that the incoming request does not contain potentially malicious input. By default, input validation is enabled. It is possible to disable request validation by using the ValidateInputAttribute attribute, as in the following example:

        [ValidateInput(false)]
        public ActionResult SomeAction() {
            return View();
        }

    However, many web applications have individual form fields that need to allow HTML, while the remaining fields should not. The ValidateInputAttribute class now lets you specify a list of fields that should not be included in request validation.

    For example, if you are developing a blog engine, you might want to allow markup in the Body and Summary fields. These fields might be represented by two input element, each with a name attribute corresponding to the property name (“Body” and “Summary”). To disable request validation for these fields only, specify the names (comma-separated) in the Exclude property of the ValidateInput class, as in the following example:

        [ValidateInput(true, Exclude="Body, Summary")]
        public ActionResult About() {
            return View();
        }

    Helpers Convert Underscores to Hyphens for HTML Attribute Names Specified Using Anonymous Objects

    Helper methods let you specify attribute name/value pairs using an anonymous object, as in the following example:

        Html.TextBox("Name", "Value", new {title = "Title"})

    This approach doesn’t let you use hyphens in the attribute name, because a hyphen cannot be used for a property name in ASP.NET. However, hyphens are important for custom HTML5 attributes; for example, HTML5 uses the “data-“ prefix.

    At the same time, underscores cannot be used for attribute names in HTML, but are valid within property names. Therefore, if you specify attributes using an anonymous object, and if the attribute names include an underscore,, helper methods will convert the underscores to hyphens. For example, the following helper syntax uses an underscore:

        Html.TextBox("Name", "Value", new {data_required = "true"})

    The previous example renders the following markup when the helper runs:

     <input data-required="true" id="Name" name="Name"
           type="textbox" value="Value" />

    Bug Fixes

    The default object template for the EditorFor and DisplayFor template helpers now supports the ordering specified in the DisplayAttribute.Order property. (In previous versions, the Order setting was not used.)

    Client validation now supports validation of overridden properties that have validation attributes applied.

    JsonValueProviderFactory is now registered by default.

    Breaking Changes

    The order of execution for exception filters has changed for exception filters that have the same Order value. In ASP.NET MVC 2 and earlier, exception filters on the controller with the same Order as those on an action method were executed before the exception filters on the action method. This would typically be the case when exception filters were applied without a specified Order value. In ASP.NET MVC 3, this order has been reversed so that the most specific exception handler executes first. As in earlier versions, if the Order property is explicitly specified, the filters are run in the specified order.

    Known Issues

    During installation, the EULA acceptance dialog box displays the license terms in a window that is smaller than intended.

    Razor views do not have IntelliSense support nor syntax highlighting. It is anticipated that support for Razor syntax in Visual Studio will be included as part of a later release.

    When you are editing a Razor view (CSHTML file), the Go To Controller menu item in Visual Studio will not be available, and there are no code snippets.

    When using the @model syntax to specify a strongly typed CSHTML view, language-specific shortcuts for types are not recognized. For example, @model int will not work, but @model Int32 will work. The workaround for this bug is to use the actual type name when you specify the model type.

    When using the @model syntax to specify a strongly typed CSHTML view (or @ModelType to specify a strongly typed VBHTML view), nullable types and array declarations are not supported. For example, @model int? is not supported. Instead, use @model Nullable<Int32>. The syntax @model string[] is also not supported; instead, use @model IList<string>.

    When you upgrade an ASP.NET MVC 2 project to ASP.NET MVC 3, make sure to add the following to the appSettings section of the Web.config file:

    <appSettings>
      <add key="enableSimpleMembership" value="false" />
    </appSettings>

    There’s a known issue that causes Forms Authentication to always redirect unauthenticated users to ~/Account/Login, ignoring the forms authentication setting used in Web.config. The workaround is to add the following app setting.

          <add key="autoFormsAuthentication" value="false" />

    Disclaimer

    © 2011 Microsoft Corporation. All rights reserved. This document is provided “as-is.” Information and views expressed in this document, including URL and other Internet Web site references, may change without notice. You bear the risk of using it.

    This document does not provide you with any legal rights to any intellectual property in any Microsoft product. You may copy and use this document for your internal, reference purposes.

新的 都是坏的?!

mikel阅读(1076)

《疯狂原始人》里面的:新的 都是坏的!

一句话描述了那些恐惧变化的人的心态,为什么新的都是坏的?因为大家都墨守成规,习惯了现有的环境,不希望被改变,只要出现新的东西,都不假思索的去否定,然后拒绝接受,这就导致了一个结果,没有创新,也没有进步。

互联网上新的东西每天都会诞生,老的东西也每天都会消亡,没有永远不变的敌人,也没有永远不变的模式能够适应互联网的发展,这么多年来,从开始人们怀疑电子商务是骗人的,不敢使用支付宝等在线支付,到现在人们习以为常,就像使用银行卡刷卡一样成为了消费习惯,一切都是因为创新造成的改变,打破了人们的生活模式,让世界进步。

从线上到线下,都面临着一个问题:转型!线上的像移动互联网转,线下的向互联网转,传统企业的基因中要融入互联网基因,互联网企业不复存在,大家都是了,变化带来得是变革,彻底改变了人们的思维,新的模式、新的产品、新的营销彻底的充斥了各大媒体报道,甚至媒体都被自媒体这种新的形式给改变了!还能说新的 都是坏的?!

 

[转载]使用NodeJS将XML解析成JSON及性能比较 - 推酷

mikel阅读(1149)

[转载]使用NodeJS将XML解析成JSON及性能比较 – 推酷.

并不是所有的API都是以JSON格式返回的。我们有时侯不得不处理一些XML。幸运的是有一个NodeJS模块 xml2js 可以帮你做这件事。

比如,我们要处理下面这段XML

<?xml version="1.0" encoding="UTF-8" ?>
<business>
    <company>Code Blog</company>
    <owner>Nic Raboy</owner>
    <employee>
        <firstname>Nic</firstname>
        <lastname>Raboy</lastname>
    </employee>
    <employee>
        <firstname>Maria</firstname>
        <lastname>Campos</lastname>
    </employee>
</business>

现在创建一个项目目录,添加一个JavaScript文件,它会进行,如果你使用Terminal,你就可以这样:

mkdir TestApp
cd TestApp
touch app.js

最关键的一点是安装xml2js库,所以你可以在命令行输入

npm install xml2js

安装成功之后你会在当前目录发现一个 node_modules目录,里面有一个xml2js。

在app.js中添加如下内容:

var parseString = require('xml2js').parseString;
var xml = '<?xml version="1.0" encoding="UTF-8" ?><business><company>Code Blog</company><owner>Nic Raboy</owner><employee><firstname>Nic</firstname><lastname>Raboy</lastname></employee><employee><firstname>Maria</firstname><lastname>Campos</lastname></employee></business>';
parseString(xml, function (err, result) {
    console.dir(JSON.stringify(result));
});

现在你可以用Node.JS运行你的应用了,使用下面的命令:

node app.js

如果一切顺序你会得到JSON格式的输出:

{
    "business": {
        "company": [ "Code Blog" ],
        "owner": [ "Nic Raboy" ],
        "employee": [
            {
                "firstname": [ "Nic" ],
                "lastname": [ "Raboy" ]
            },
            {
                "firstname": [ "Maria" ],
                "lastname": [ "Campos" ]
            }
        ]
    }
}

有一点需要注意,XML字符串元素转换成了JSON的数组。你可能期望 { owner: “Nic Raboy” } 但实际输出的是 { owner: [ “Nic Raboy” ] },但这不是什么大问题。

注* 可以通过 explicitArray: false 来解决:

xml2js.parseString(xmlStr, { explicitArray : false, ignoreAttrs : true }, callbackMethod);

性能比较

有人指出xml2js的速度过慢,有人做过性能测试,  htmlparser2 的性能提升大约5倍以上,如下图 ,测试 地址

另外还有一个使用C语言写的xml解析器 node-expat ,性能更好,

安装

npm i node-expat

不过使用也很“底层“, 对性能有一定要求的应用可以尝试一下:

(function () {
  "use strict";

  var expat = require('node-expat')
  var parser = new expat.Parser('UTF-8')

  parser.on('startElement', function (name, attrs) {
    console.log(name, attrs)
  })

  parser.on('endElement', function (name) {
    console.log(name)
  })

  parser.on('text', function (text) {
    console.log(text)
  })

  parser.on('error', function (error) {
    console.error(error)
  })

  parser.write('<html><head><title>Hello World</title></head><body><p>Foobar</p></body></html>')

}())

不过还有一些项目对 expat 进行了封装,简化了调用接口,比如: xml2obj-stream

原文地址:点此