Explicit casting doesn't work in default model

2020-05-03 13:09发布

问题:

I am using ASP.NET MVC2 and Entity Framework. I am going to simplify the situation a little; hopefully it will make it clearer, not more confusing!

I have a controller action to create address, and the country is a lookup table (in other words, there is a one-to-many relationship between Country and Address classes). Let's say for clarity that the field in the Address class is called Address.Land. And, for the purposes of the dropdown list, I am getting Country.CountryID and Country.Name.

I am aware of Model vs. Input validation. So, if I call the dropdown field formLand - I can make it work. But if I call the field Land (that is, matching the variable in Address class) - I am getting the following error:

"The parameter conversion from type 'System.String' to type 'App.Country' failed because no type converter can convert between these types."

OK, this makes sense. A string (CountryID) comes from the form and the binder doesn't know how to convert it to Country type. So, I wrote the converter:

namespace App {
    public partial class Country {
        public static explicit operator Country(string countryID) {
            AppEntities context = new AppEntities();
            Country country = (Country) context.GetObjectByKey(
                new EntityKey("AppEntities.Countries", "CountryID", countryID));
            return country;
        }
    }
}

FWIW, I tried both explicit and implicit. I tested it from the controller - Country c = (Country)"fr" - and it works fine. However, it never got invoked when the View is posted. I am getting the same "no type converter" error in the model.

Any ideas how to hint to the model binder that there is a type converter? Thanks

回答1:

A type converter is not the same as an explicit or implicit conversion, it's an object that converts values between various types.

I think you need to create a class inherited from TypeConverter that converts between Country and other types, and apply the TypeConverterAttribute to your class to specify the converter to use :

using System.ComponentModel;

public class CountryConverter : TypeConverter
{
    // override CanConvertTo, CanConvertFrom, ConvertTo and ConvertFrom
    // (not sure about other methods...)
}

[TypeConverter(typeof(CountryConverter))]
public partial class Country
{

...

}