我正在使用 ASP.NET MVC2 和实体框架。我将稍微简化一下情况;希望它能让它更清晰,而不是更混乱!
我有一个控制器操作来创建地址,国家/地区是一个查找表(换句话说,国家/地区和地址类之间存在一对多关系)。为了清楚起见,我们假设 Address 类中的字段称为 Address.Land。并且,出于下拉列表的目的,我获取了 Country.CountryID 和 Country.Name。
我知道模型与输入验证 http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html。所以,如果我调用下拉字段formLand- 我可以让它发挥作用。但如果我调用该字段Land(即匹配 Address 类中的变量) - 我收到以下错误:
"参数从类型转换
“System.String”以输入“App.Country”
失败,因为没有类型转换器可以
这些类型之间进行转换。”
好吧,这是有道理的。字符串 (CountryID) 来自表单,绑定器不知道如何将其转换为 Country 类型。所以,我写了转换器:
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,我尝试了显式和隐式。我从控制器测试了它 -Country c = (Country)"fr"
- 而且效果很好。然而,当视图被发布时它从未被调用。我在模型中遇到相同的“无类型转换器”错误。
任何想法如何向模型绑定者暗示有is类型转换器?
谢谢
类型转换器与显式或隐式转换不同,它是在各种类型之间转换值的对象。
我认为你需要创建一个继承自的类TypeConverter
之间转换Country
和其他类型,并应用TypeConverterAttribute
到您的类来指定要使用的转换器:
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
{
...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)