簡體   English   中英

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

[英]How to clear textboxes besides using JS

我正在使用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
}

顯然,這些屬性是不可為空的,因此在我的“ Create視圖”中,它們在頁面加載時顯示為原樣( 忽略第二個文本框 ):

在此處輸入圖片說明

現在我的目標是清除那些文本框,所以它們只是空白..因此,我使用JS通過執行以下操作來實現:

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

我在這些輸入字段上放置了一個名為clear-textbox的類..效果很好..但是現在在我的HttpPost Create Action我有條件語句檢查其他字段是否有效,是否不返回對象。

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

這將導致重新顯示“ Create視圖,其中包含用戶已經輸入的值以及一個需要更改的屬性下方的錯誤消息。這就是問題所在。 重新加載Create視圖后.. 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幫助器 ,它將根據您的特殊需求進行操作。 讓我知道您是否想要該代碼...

您也可以參考此鏈接

您可以將默認值設置為文本框的data- attribute,並在它們匹配時將其清除。 喜歡:

$(".clear-textbox").each(function(){
    var $this = $(this);
    if( $this.val() == $this.data().defaultvalue ) $this.val('');
});

不知道文本框是如何呈現的,很難給出答案。 但是,我假設您正在使用類似

@Html.TextBoxFor

要么

@Html.EditorFor

有兩種方法可以做到這一點。

1.將DisplayFormat屬性添加到模型字段,並使用EditorFor:

public class TestClass
{
    public int ID { get; set; }
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:#.#}")]
    public decimal DecimalProperty { get; set; }
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:#.#}")]  
    public decimal SecondDecimalProperty { get; set; }
}


@Html.EditorFor(model => model.DecimalProperty)

2.使用內聯格式屬性:

@Html.TextBoxFor(model => model.DecimalProperty, "{0:#.#}")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM