Nei*_*eil 4 asp.net-mvc modelbinders
鉴于以下模型,
public class A
{
public string Name { get; set; }
}
public class B
{
public string Address { get; set; }
public A InstanceOfA { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
视图,
<%= Html.TextBox("A.Name") %>
Run Code Online (Sandbox Code Playgroud)
和控制器
UpdateModel<B>(b, collection.ToValueProvider());
Run Code Online (Sandbox Code Playgroud)
我的b实例将包含A的属性,其中包含Name的空字符串.
无论如何,如果没有为name输入值,UpdateModel是否将A属性设置为null?
为了澄清,这是一个简单的案例,我的真实世界场景包含具有数百种此类属性的数据模型.这些数据模型的定义不在我手中.因此,我需要针对一般情况的解决方案,即如果没有输入值,则不创建属性.
进一步澄清:我需要这个在编辑场景中工作,也就是说,将A.Name设置为"foo"的b实例编辑为将A.Name设置为"",我希望A为null.
我刚刚发现了这种行为(由于检查约束而意外),我认为这是一个错误.我想知道有多少开发人员现在无意中将空字符串保存到他们的db而不是null?:-)
无论如何,我将更多地探讨这一点,看看是否有更好的解决方案.
更新:
这是一个解决方案:
using System.ComponentModel;
using System.Web.Mvc;
namespace CustomerWebsite.Mvc
{
public sealed class EmptyStringToNullModelBinder : DefaultModelBinder
{
protected override void SetProperty(ControllerContext controllerContext,
ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
{
if ((value != null)
&& (value.GetType() == typeof(string)
&& ((string)value).Length == 0))
{
value = null;
}
base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在Application_Start中放这个:
ModelBinders.Binders.DefaultBinder = new EmptyStringToNullModelBinder();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3991 次 |
| 最近记录: |