如何在ASP.NET MVC Preview 5中使用新的ModelBinder类
时间:2020-03-05 18:45:04 来源:igfitidea点击:
我们会注意到,预览5在其发行说明中包括以下内容:
Added support for custom model binders. Custom binders allow you to define complex types as parameters to an action method. To use this feature, mark the complex type or the parameter declaration with [ModelBinder(…)].
因此,我们如何实际使用此功能,以便在Controller中进行类似的工作:
public ActionResult Insert(Contact contact) { if (this.ViewData.ModelState.IsValid) { this.contactService.SaveContact(contact); return this.RedirectToAction("Details", new { id = contact.ID} } }
解决方案
回答
好吧,我调查了这个。 ASP.NET为注册IControlBinders的实现提供了一个通用位置。他们还通过新的Controller.UpdateModel方法掌握了此工作的基础。
因此,我基本上通过创建一个IModelBinder实现来组合这两个概念,该实现对modelClass的所有公共属性都执行与Controller.UpdateModel相同的操作。
public class ModelBinder : IModelBinder { public object GetValue(ControllerContext controllerContext, string modelName, Type modelType, ModelStateDictionary modelState) { object model = Activator.CreateInstance(modelType); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(model); foreach (PropertyDescriptor descriptor in properties) { string key = modelName + "." + descriptor.Name; object value = ModelBinders.GetBinder(descriptor.PropertyType).GetValue(controllerContext, key, descriptor.PropertyType, modelState); if (value != null) { try { descriptor.SetValue(model, value); continue; } catch { string errorMessage = String.Format("The value '{0}' is invalid for property '{1}'.", value, key); string attemptedValue = Convert.ToString(value); modelState.AddModelError(key, attemptedValue, errorMessage); } } } return model; } }
我们需要在Global.asax.cs中添加以下内容:
protected void Application_Start() { ModelBinders.Binders.Add(typeof(Contact), new ModelBinder());
回答
http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx