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

我使用一个表来发表的信息和我的模型验证内置到它。 我知道我可以通过使用以下的任一验证字段:

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

这两种方法都仅仅返回一个HTML列表(的ValidationSummary)或跨度(ValidateionMessageFor)。

我想这样做的只是得到一个真或假的陈述,如果字段是合法还是不(或NULL如果没有),这样我可以做一些定制的造型到包含输入,或者甚至在标签的盒子。

有谁知道,如果有这样的代码,将做到这一点,像@Html.IsValid(x => x.FirstName)

这里是我的模型和视图。 该模型是通过拉动和正确验证,它仅仅是一个我是否可以得到一个布尔值,而不是HTML字符串的问题。

模型:

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>

--------------解决方案-------------

有谁知道,如果有这样的代码,将做到这一点,如@ Html.IsValid(X => 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>
}

分类:C# 时间:2015-03-15 人气:0
本文关键词: asp.net的MVC 3
分享到:

相关文章

Copyright (C) 55228885.com, All Rights Reserved.

55228885 版权所有 京ICP备15002868号

processed in 0.420 (s). 10 q(s)