在我的模型类中,我有多个属性是“受保护的内部集”。一旦创建了这些属性,就不能对其进行修改。话虽如此,我很难创建一个模型绑定器,它将允许在创建时设置这些属性。为了能够只设置一次这些属性,最好的方法是什么?
发布于 2012-05-29 23:24:51
不幸的是,这不是你可以自动完成的事情。您必须为每种类型创建一个唯一的模型绑定器,然后使用构造函数参数创建对象。
发布于 2012-08-13 08:50:19
我使用一个定制的模型绑定器完成了这项工作。我不仅有私有的setter,而且我的MVC操作的参数是一个接口,而且我没有无参数的构造函数(真棒!);它们都不能使用默认的模型绑定器。
在您的例子中,您只需为您的类型创建一个自定义模型绑定器。使用默认值创建类的新实例。然后只需使用反射来设置类的属性。反射方法并不关心属性的可访问性。如下所示:
// assuming your class looks like this
public class MyClass
{
public int MyInt { get; private set; }
public string MyString { get; private set; }
public MyClass(int myInt, string myString)
{
MyInt = myInt;
MyString = myString;
}
}
// model binder is like this
public class MyModelBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext,
ModelBindingContext bindingContext,
Type modelType)
{
// initialize with default values, they will be overwritten
MyClass myClass = new MyClass(default(int), default(string));
// get the reflection info on the int property
PropertyInfo intProperty = typeof(MyClass).GetProperty("MyInt");
// get the int value from the request
int myIntValue = int.Parse(bindingContext.ValueProvider
.GetValue(intProperty.Name).AttemptedValue);
// btw, attempted value is a string
// set the property value, SetValue ignores accessibility modifiers
intProperty.SetValue(myClass, myIntValue, null);
// do the same stuff for MyString property
PropertyInfo stringProperty = typeof(MyClass).GetProperty("MyString");
string myStringValue = bindingContext.ValueProvider
.GetValue(stringProperty.Name).AttemptedValue;
stringProperty.SetValue(myClass, myStringValue, null);
return myClass;
}
}
// Your controller action is like this
public ActionResult MyAction([ModelBinder(typeof(MyModelBinder))]
MyClass myClass)
{
...
}我想您可以只将正确的值传递到构造函数中,而不使用反射来设置它们:
...
int myIntValue = int.Parse(bindingContext.ValueProvider
.GetValue(intProperty.Name).AttemptedValue);
string myStringValue = bindingContext.ValueProvider
.GetValue(stringProperty.Name).AttemptedValue;
MyClass myClass = new MyClass(myIntValue, myStringValue);
...但是如果你需要做更多的事情,反射可以让你绕过访问修饰符的限制(当然是出于有效的基础设施原因!:D)。在我的例子中,我不想为每个可以实现接口的类编写一个模型绑定器,所以我使用了更多的反射来匹配类,找到一个构造函数,将默认值传递给它,然后循环遍历类上的每个属性,并从请求值设置它。在运行基于消息的操作之前,我有一个单独的方法来验证消息。
发布于 2012-05-30 19:08:37
您是否可以让受保护的set方法仅在尚未设置的情况下设置私有字段?
public string PropertyName
{
get
{
return this.privateField;
}
protected set
{
if (this.privateField == null)
{
this.privateField = value;
}
}
}
private string privateField;https://stackoverflow.com/questions/10802061
复制相似问题