MVC 4视图中的错误

时间:2013-02-04 16:27:43

标签: asp.net asp.net-mvc-4

有没有办法检查给定对象在ASP.NET MVC 4中是否有错误。

类似

    @Html.PasswordFor(model => model.Username, new { placeholder = Html.DisplayFor(model => model.Username) })
    @if(Html.ErrorFor(model => model.Username)) {
    <small class="error">@Html.ValidationMessageFor(model => model.Username)</small>
}

更新 它不是整个模型,但我需要检查给定的元素,所以f.eks。 do mode.Username有错误!

2 个答案:

答案 0 :(得分:2)

我通过创建2个方法解决了这个问题。

    public static bool HasErrorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
    {
        if (expression == null)
            throw new ArgumentNullException("expression");

        string modelName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
        if (!htmlHelper.ViewData.ModelState.ContainsKey(modelName))
            return false;

        ModelState modelState = htmlHelper.ViewData.ModelState[modelName];
        return modelState.Errors.Count > 0;
    }
    public static MvcHtmlString GetErrorMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
    {
        if (expression == null)
            throw new ArgumentNullException("expression");

        string modelName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
        if (!htmlHelper.ViewData.ModelState.ContainsKey(modelName))
            return new MvcHtmlString(null);

        ModelState modelState = htmlHelper.ViewData.ModelState[modelName];
        if (modelState.Errors.Count > 0)
        {
            return new MvcHtmlString(modelState.Errors.FirstOrDefault().ErrorMessage);
        }

        return new MvcHtmlString(null);
    }

以及如何使用

<div class="row">
    <div class="six columns">
        @Html.TextBoxFor(model => model.Username, new { placeholder = Html.GetDisplayFor(model => model.Username) })
        @if (Html.HasErrorFor(model => model.Username))
        {
        <small class="error">@Html.GetErrorMessageFor(model => model.Username)</small>
        }
    </div>
</div>

答案 1 :(得分:0)

使用ModeState.IsValid属性检查模型的有效性

if(ModelState.IsValid)
{
 //DO update/insertion/deletion
}
else
{
 // return your view
}

显示错误。 Read this Post for More Info On ModelState Erro Display

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();

for Specific属性尝试ModelState["yourProperty"]。获取模型状态字典对象,该对象包含模型的状态和模型绑定验证。

        if (ModelState["yourProperty"].Errors.Count >0) //then error