Car*_*osa 13 c# asp.net razor asp.net-mvc-3
我正在为某个viewModel属性开发客户端和服务器端验证.
在.cshtml文件中我把它:
@Html.DropDownListFor(model => model.EntityType.ParentId, Model.ParentTypeList, "")
@Html.ValidationMessageFor(model => model.EntityType.ParentId)
Run Code Online (Sandbox Code Playgroud)
在Controller中进行业务验证
catch (BusinessException e)
{
ModelState.AddModelError("EntityType.ParentId", Messages.CircularReference);
}
Run Code Online (Sandbox Code Playgroud)
以上工作符合预期:如果捕获到异常,则消息将显示在下拉列表旁边.
但是,我发现这种方式并不是很优雅.在cshtml,我使用一种方法来生成有关验证的所有必需信息.在控制器中,我必须知道确切的Key字符串并使用它.
这样做有没有更好的方法?
Dar*_*rov 24
您可以编写一个扩展方法,该方法将为键而不是字符串采用lambda表达式:
public static class ModelStateExtensions
{
public static void AddModelError<TModel, TProperty>(
this ModelStateDictionary modelState,
Expression<Func<TModel, TProperty>> ex,
string message
)
{
var key = ExpressionHelper.GetExpressionText(ex);
modelState.AddModelError(key, message);
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用此方法:
catch (BusinessException e)
{
ModelState.AddModelError<MyViewModel, int>(
x => x.EntityType.ParentId,
Messages.CircularReference
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4373 次 |
| 最近记录: |