【问题标题】:Add CSS Class Conditionally - Asp.net有条件地添加 CSS 类 - Asp.net
【发布时间】:2017-06-28 11:59:20
【问题描述】:

我浏览过一些类似问题的帖子,但还没有找到任何好的解决方案。

我正在尝试通过检查是否存在任何错误来在 div 中添加一个 CSS 类。如下所示

<div class="form-group m-t-20 @((@Html.ValidationMessage("Email") != null && @Html.ValidationMessage("Email").ToString() != "") ? "has-danger has-error" : "")">

但是当我做检查元素时,@Html.ValidationMessage("Email") 似乎永远不会为空(所以总是添加has-danger has-error),即使没有Email 的验证消息,比如

@Html.ValidationMessage("Email") 翻译成&lt;span class="field-validation-valid" data-valmsg-for="Email" data-valmsg-replace="true"&gt;&lt;/span&gt;

那么有没有办法检查是否存在某些错误然后添加一个 css 类?另外我会意识到我不需要为这个小目的创建新类(.cs 文件)。

PS:我正在使用 Asp.net MVC。在后端我添加这样的错误ModelState.AddModelError("Email", "User already exists");

【问题讨论】:

  • 为什么不直接使用已经添加的类名——field-validation-valid(如果有效)和field-validation-error(如果无效)
  • @StephenMuecke 我想给div添加自定义css类,我的结构是&lt;div class="custom-class"&gt;&lt;input /&gt;&lt;/div&gt;。类名在这里重要吗?
  • 目的是什么?为什么不直接设置 field-validation-error 类的样式?

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


【解决方案1】:

如果您想在 View 上检查模型中的错误,您应该检查 ViewData.ModelState 属性。

像这样:

@if (!ViewData.ModelState.IsValid && ViewData.ModelState["Email"].Errors.Count > 0))
{
   <span>your message<span/>
}

三元版:

@((!ViewData.ModelState.IsValid && ViewData.ModelState["Email"].Errors.Count > 0)? "your message": String.Empty)

【讨论】:

  • IsValidField 它给了我错误Compiler Error Message: CS1061: 'System.Web.Mvc.ViewDataDictionary&lt;HospitalManagament.Models.SignupModel&gt;' does not contain a definition for 'IsValidField' and no extension method 'IsValidField' accepting a first argument of type 'System.Web.Mvc.ViewDataDictionary&lt;HospitalManagament.Models.SignupModel&gt;' could be found (are you missing a using directive or an assembly reference?)
  • @Junaid 你用的是什么版本的 MVC?
  • 我正在使用v5.2.3.0
  • 我尝试了您的解决方案,但在两种情况下(错误和无错误)仍然添加 has-danger has-error
  • @Junaid 以及 ViewData.ModelState["Email"] 里面到底有什么错误?也许你应该检查一下 String.Empty?
猜你喜欢
  • 1970-01-01
  • 2015-01-29
  • 1970-01-01
  • 2010-10-19
  • 2020-07-30
  • 1970-01-01
  • 2011-02-18
  • 2015-01-05
  • 1970-01-01
相关资源
最近更新 更多