javascript - 除了使用JS之外,如何清除文本框

标签 javascript c# jquery asp.net-mvc

我正在使用 MVC 构建一个应用程序,这个问题与 Create 页面和操作有关。

假设我的模型有 2 个小数属性以及其他属性,但对于本例来说不是必需的:

public class TestClass
{
    public int ID { get; set; }
    public decimal DecimalProperty { get; set; }
    public decimal SecondDecimalProperty { get; set; }
    // more properties below this, but deemed unnecessary for this question
}

显然这些属性不可为 null,因此在我的 Create View 中,它们在页面加载时显示为这样(忽略第二个文本框):

enter image description here

现在我的目标是清除这些文本框,所以它们只是空白..所以我使用 JS 来实现这一点:

$(".clear-textbox").val("");

我在这些输入字段上放置了一个名为 clear-textbox 的类.. 工作完美......但现在在我的 HttpPost Create Action 中,我有条件语句检查以查看是否其他字段是有效的,如果不返回对象..就像这样:

if (object.property== 0)
{
    ModelState.AddModelError("property", "This field is required!");
    return View(object);
}

这会导致 Create View 重新显示,其中包含用户已输入的值,以及需要更改的一个属性下方的错误消息。问题出在。重新加载 Create View 后,clear-textbox 的脚本也会重新加载,从而生成 DecimalPropertySecondDecimalProperty > 为空文本框..而不是保留用户最初输入的内容。

所以我的问题是,除了使用 JavaScript 之外,还有其他方法可以清除小数属性的文本框吗?

感谢任何帮助。

<小时/>

更新

这是 cshtml。

<div class="form-group">
    @Html.LabelFor(model => model.DecimalProperty, htmlAttributes: new { @class = "control-label col-md-4" })
    <div class="col-md-8">
        @Html.EditorFor(model => model.DecimalProperty, new { htmlAttributes = new { @class = "form-control clear-textbox" } })
        @Html.ValidationMessageFor(model => model.DecimalProperty, "", new { @class = "text-danger" })
    </div>
</div>

最佳答案

您必须通过加载时的 Javascript 来完成此操作,如下所示

$(".clear-textbox").each(function(){
    if($(this).val() <= 0 ) 
        $(this).val("");
});

或者

您可以创建自己的 MVC Html Helper,它将根据您的特殊需求执行您需要的操作。如果您需要代码,请告诉我...

You can also refer this link

关于javascript - 除了使用JS之外,如何清除文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41622525/

相关文章:

C# OpenXML - 表属性 - 设置从左侧缩进

jquery - 使用 Jquery 在加载时显示 div

javascript - baseurl 在 Jekyll 中不起作用

javascript - React Native 中的 Flex header 布局

c# - C# 中的可写字节流风格功能

jquery - 使用 Twitter Bootstrap 自动启动和停止 YouTube 视频

javascript - 多页 jquerymobile 文档第二页上的按钮的单击事件不会触发

javascript - 有没有办法用 D3.js 修改 Vega 图表?

javascript - 单页上具有多个实例的 jQuery 图像旋转器

c# - MVC 6 HttpResponseException