Hi, I'm studing MVC3 and run into stupid problem. I hope you advise.
I've class library, where my domain classes reside. This library is used in several applications.
While they were web forms, it works perfect.
How I did use them:
Somewhere on page.aspx I use listbox server contol which binds to the Company field via such expression:Code:// Domain objects [TypeConverter(typeof (CompanyConverter))] public class Company : ValidStateDomainObject { //... } public class CompanyConverter : TypeConverter { public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { //... } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { // context is null for webpages and mvc projects return sourceType == typeof (string) || base.CanConvertFrom(context, sourceType); } //... }
Under the hood Binding manager calls TypeConverter to instantiate Company object from the value of listbox and binds it to the appropriate Employee.Code:BindingManager.AddBinding("ddlCompany.SelectedValue", "Employee.Company", BindingDirection.Bidirectional);
Then, in MVC3 app I'm trying to use DefaultModelBinder to get Company instance from HttpRequest:
get null in company parameter.Code:[HttpPost] public ActionResult Create([Bind(Exclude = "Id")]Company company) { // company = null !!!!! if I use TypeConverter if (!ModelState.IsValid) return View(company); CompanyService.SaveOrUpdate(company); return RedirectToAction("Index"); }
I've stepped into MVC3 source and found out that DefaultModelBinder checks if the model is ComplexType:
and in such case returns null instead of populated objectCode:public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { ... if (!bindingContext.ModelMetadata.IsComplexType) { return null; } ... } public virtual bool IsComplexType { get { return !(TypeDescriptor.GetConverter(ModelType).CanConvertFrom(typeof(string))); } }
when finds out that object can be converted from string!!!
Unfortunately I can't switch off TypeConvereters in CanConvertFrom function as ITypeDescriptorContext context parameter is always null.
So I can not use classes with typeconverters and modelbinders in MVC3 simultaneously. Though it can be very convenient.
May be I'm doing things wrong way?
Hope you help me,
thank you in advance,
Alexander.


Reply With Quote
