如何获得MVC3模型验证的真或假输出

时间:2011-10-28 12:53:36

标签: c# asp.net-mvc-3

我正在使用表单发布信息,我的模型已经内置了验证。我知道我可以使用以下任一项来验证字段:

@Html.ValidationSummary() //To validate all fields

@Html.ValidationMessageFor(x => x.FirstName) //To validate single field

这两种方法都只返回HTML列表(For ValidationSummary)或span(ValidateionMessageFor)。

我想做的是,如果字段有效,则获取真或假(如果没有,则为null),以便我可以对包含输入的框进行自定义样式,甚至标签为了它。

有没有人知道是否有这样的代码会执行此操作,例如@Html.IsValid(x => x.FirstName)

这是我的模型和视图。该模型正在通过并正确验证,这只是一个问题,我是否可以获得布尔值而不是HTML字符串。

MODEL:

using System.ComponentModel.DataAnnotations;

namespace X.Web.Helpers
{
    public class RequestSamplesModel
    {
        [Required]
        public string FirstName { get; set; }
        [Required]
        public string LastName { get; set; }

        public string Email { get; set; }
        [Required]
        public string Line1 { get; set; }
        [Required]
        public string Line2 { get; set; }
        [Required]
        public string City { get; set; }
        [Required]
        public string Postcode { get; set; }
        [Required]
        public string Country { get; set; }
    }
}

查看:

@{
    Layout = "~/Views/Shared/_PlainLayout.cshtml";
}
@using X.Web.Helpers
@model RequestSamplesModel

<form action="/Site/RequestSamples" method="POST">
    <div class="form-item">
        <span>First Name:</span>@Html.TextBoxFor(x => x.FirstName)</div>
    <div class="form-item">
        <span>Last Name:</span>@Html.TextBoxFor(x => x.LastName)</div>
    <div class="form-item">
        <span>Email:</span>@Html.TextBoxFor(x => x.Email)</div>
    <div class="form-item">
        <span>Address 1:</span>@Html.TextBoxFor(x => x.Line1)</div>
    <div class="form-item">
        <span>Address 2:</span>@Html.TextBoxFor(x => x.Line2)</div>
    <div class="form-item">
        <span>City:</span>@Html.TextBoxFor(x => x.City)</div>
    <div class="form-item">
        <span>Postcode:</span>@Html.TextBoxFor(x => x.Postcode)</div>
    <div class="form-item">
        <span>Country:</span>@Html.TextBoxFor(x => x.Country)</div>
    <div class="form-item">
        <input class="submit-button" type="image" src="/_content/images/email-submit.gif" /></div>
</form>

1 个答案:

答案 0 :(得分:3)

  

有没有人知道是否有这样的代码可以做到这一点,比如   @ Html.IsValid(x =&gt; x.FirstName)

不,内置的代码不存在。但是写一个以便现在有:

是微不足道的
public static class HtmlExtensions
{
    public static bool IsValid<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper, 
        Expression<Func<TModel, TProperty>> expression
    )
    {
        var modelState = htmlHelper.ViewData.ModelState;
        var name = ExpressionHelper.GetExpressionText(expression);
        var key = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
        ModelState value;
        return !modelState.TryGetValue(key, out value) || 
               value.Errors.Count == 0;
    }
}

现在,在您的视图中,只需将扩展方法纳入范围即可:

@if (Html.IsValid(x => x.FirstName))
{
    @:<div>Super, the first name is valid</div>
}