【问题标题】:Webmatrix how to add a class if input type text box is not empty?如果输入类型文本框不为空,Webmatrix如何添加一个类?
【发布时间】:2014-08-20 04:52:22
【问题描述】:

如果输入类型文本框不为空或为空,我想添加一个类。我正在尝试做这样的事情。

.cshtml

@{
    var value= string.IsNullOrEmpty;
}

<form action="">
    <input type="text" value="@value" class="@(value=!null ? "thisclass" : "")">
</form>

我很抱歉这个不好的例子,但我真的不知道如何解释它,我没有使用 MVC 或数据库,这是一个简单的输入 type="text" 框。请帮忙!

【问题讨论】:

  • 如果你将value改为string.Empty,并与@(string.IsNullOrWhiteSpace(value) ? "thisclass" : "")进行比较,我认为它会更好。 :)

标签: c# asp.net razor webmatrix


【解决方案1】:

开始了一个新的 MVC 项目。

这是我在 Index.cshtml 中使用的代码,它运行良好。 (我在文本字段中得到一个红色背景)

@{
    ViewBag.Title = "Home Page";

    var value = string.Empty;
}

<style type="text/css">
    .testclass {
        background-color: red;
    }
</style>

<div class="jumbotron">
    <h1>ASP.NET</h1>
    <input type="text" class="@(string.IsNullOrWhiteSpace(value) ? "testclass" : "")" />
    <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
    <p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
</div>

【讨论】:

  • 对不起,如果有人在输入文本框中写了一些东西但它已经是红色的,我只想添加这个类。
  • 啊,那就把比较翻转到!string.IsNullOrWhiteSpace,这样就只在不为空的时候才添加类。
  • 如果您希望它在编写时添加类,您应该查看 javascript。有一个名为onkeyup 的事件,您可以在其中检查文本框是否包含任何文本,然后您可以根据需要添加/删除该类。要使 MVC 工作,您必须在页面呈现之前设置该值。
  • 我认为值标签是必需的。 &lt;input type="text" value="@???" ...
【解决方案2】:

正如 NoLifeKing 所说,这是测试输入是否为空并相应更改其类的服务器端解决方案:

<input type="text" id="testinput" value="@value" 
   class="@(string.IsNullOrEmpty(value) ? "thisclass" : "")"  />

如果你希望输入类在你写的时候改变,你必须使用jquery,比如:

$(document).ready(function () {
    $('#testinput').keyup(function () {
        if (!this.value) {
            $(this).addClass('thisclass');
        } else {
            $(this).removeClass('thisclass');
        }
    });
});

【讨论】:

    猜你喜欢
    • 2018-09-20
    • 2012-12-10
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 2018-11-04
    相关资源
    最近更新 更多