Ren*_*ené 8 c# custom-model-binder asp.net-mvc-3
我正在使用ASP.NET MVC 3 RTM,我有一个这样的视图模型:
public class TaskModel
{
// Lot's of normal properties like int, string, datetime etc.
public TimeOfDay TimeOfDay { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
该TimeOfDay属性是我自定义的结构,非常简单,所以我不在此处.我已经制作了一个自定义模型绑定器来绑定这个结构.模型绑定器非常简单:
public class TimeOfDayModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
try
{
// Let the TimeOfDay struct take care of the conversion from string.
return new TimeOfDay(result.AttemptedValue, result.Culture);
}
catch (ArgumentException)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Value is invalid. Examples of valid values: 6:30, 16:00");
return bindingContext.Model; // Also tried: return null, return value.AttemptedValue
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的自定义模型绑定器工作正常,但问题是当用户提供的值无法转换或解析时.当发生这种情况时(当TimeOfDay构造函数抛出时ArgumentException),我添加了一个模型错误,该错误在视图中正确显示,但是用户键入的值(无法转换)将丢失.用户键入值的文本框只是空的,而在HTML源中,value属性设置为空字符串:"".
编辑:我想知道是否可能是我的编辑器模板出错了,所以我在这里包括它:
@model Nullable<TimeOfDay>
@if (Model.HasValue)
{
@Html.TextBox(string.Empty, Model.Value.ToString());
}
else
{
@Html.TextBox(string.Empty);
}
Run Code Online (Sandbox Code Playgroud)
如何在发生绑定错误时确保该值不会丢失,以便用户可以更正该值?
Ren*_*ené 17
啊哈!我终于找到了答案!这篇博文给出了答案.我缺少的是打电话给ModelState.SetModelValue()我的模型活页夹.所以代码是这样的:
public class TimeOfDayModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
try
{
// Let the TimeOfDay struct take care of the conversion from string.
return new TimeOfDay(result.AttemptedValue, result.Culture);
}
catch (ArgumentException)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Value is invalid. Examples of valid values: 6:30, 16:00");
// This line is what makes the difference:
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, result);
return bindingContext.Model;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我希望这可以拯救别人免受我经历过的挫折时间.
| 归档时间: |
|
| 查看次数: |
1820 次 |
| 最近记录: |