【IT168 技术文档】在刚发布的ASP.NET MVC Beta版中,在UpdataModel方法中提供了一个带有IValueProvider参数的重载。那么这个IValueProvider有什么用呢?
我们先来看一个简单的场景,例如我们的blog系统有一个Post的对象,Post对象有一个Tags属性和Categories属性,他们的类型分别是:
Post.Tags : StateList<string> (BlogEngine.NET 中的一个List<T>的扩展类型)
Post.Categories : StateList<Category>
Post.Categories : StateList<Category>
假如我们要使用UpdataModel方法来对我们Post过来的Form表单数据更新到我们的Post对象中,可能会有如下的代码:
/// <summary>
/// 将提交过来的新随笔表单内容保存到数据库
/// </summary>
[AcceptVerbs("POST"), ActionName("NewPost")]
public ActionResult SaveNewPost(FormCollection form)
{
Post post = new Post();
try
{
UpdateModel(post, new[] { "Title", "Content", "Slug", "Tags", "Categories" });
}
catch
{
return View(post);
}
..
}
/// 将提交过来的新随笔表单内容保存到数据库
/// </summary>
[AcceptVerbs("POST"), ActionName("NewPost")]
public ActionResult SaveNewPost(FormCollection form)
{
Post post = new Post();
try
{
UpdateModel(post, new[] { "Title", "Content", "Slug", "Tags", "Categories" });
}
catch
{
return View(post);
}
..
}
很明显,在上面的代码中,我们用UpdateModel来更新Tags和Categories属性的时候,是不可能成功的,因为UpdateModel方法不知道怎样将Form提交过来的"Tags"和"Categories"数据转换为StateList<string>类型和StateList<Category>类型。这时候就需要我们提供一个ValueProvider,来进行这个转换。