我正在为某个viewModel属性开发客户端和服务器端验证。ValidationMessageFor与AddModelError(key,message)一起使用。关键是什么?
在.cshtml
文件我把这个:
@Html.DropDownListFor(model => model.EntityType.ParentId, Model.ParentTypeList, "")
@Html.ValidationMessageFor(model => model.EntityType.ParentId)
在控制器的业务验证
catch (BusinessException e)
{
ModelState.AddModelError("EntityType.ParentId", Messages.CircularReference);
}
上述工程按预期:如果一个异常被捕获,旁边出现消息下拉列表。
但是,我发现这种方式不是很优雅。在cshtml
中,我使用一种方法来生成有关验证的所有必需信息。在控制器中,我必须知道确切的Key字符串并使用它。
难道没有更好的方法吗?
此链接提供了一些额外的洞察力和一种不直接引用键作为字符串,而是作为表达式的方式:http://stackoverflow.com/questions/11090445/how-to-get-a-modelstate-key-of-an-item-in-列表继承人另一个资源ce提供Expression键的包装方法http://stackoverflow.com/questions/8793799/get-reference-to-object-from-c-sharp-expression – bUKaneer