问题描述
我使用的是ASP.NET MVC2和Entity Framework。我将简化情况一点;希望它会使它更清晰,不会更混乱!
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!
我有一个控制器动作来创建地址,国家是一个查找表(换句话说,国家和地址类之间的一对多关系)。让我们说清楚地址类中的字段称为Address.Land。并且,为了下拉列表的目的,我得到Country.CountryID和Country.Name。
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.
我知道。所以,如果我调用下拉字段 formLand - 我可以使它工作。但是如果我调用字段 Land (即匹配Address类中的变量) - 我得到以下错误:
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:
好的,这很有意义。字符串(CountryID)来自表单,并且binder不知道如何将它转换为Country类型。所以,我写了转换器:
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;
}
}
}
和隐式。我从控制器测试它 - 国家c =(国家)fr
- 它工作正常。然而,它从来没有被调用时发布视图。我在模型中得到相同的无类型转换器错误。
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
推荐答案
类型转换器与显式或隐式转换不同,
A type converter is not the same as an explicit or implicit conversion, it's an object that converts values between various types.
我认为你需要创建一个继承自 TypeConverter
的类,可以在 Country
和其他类型,并将 TypeConverterAttribute
应用到您的类以指定要使用的转换器:
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
{
...
}
这篇关于显式转换在默认模型绑定中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!