[英]Html.TextboxFor default value for Integer/Decimal to be Empty instead of 0
我使用默認的asp.net MVC 2語法來構造我的asp.net MVC Web應用程序的整數或十進制TextBox:
<%: Html.TextBoxFor(model => model.Loan.InterestRate) %>
非常直接,但問題本質上是我的綁定模型對象是十進制或int和不可空的事實,如果我的模型是空的,它們在頁面加載時將它們的值打印為零(0)(例如在添加模式中為CRUD模板)和零值不正確,對我的頁面驗證也無效。
我怎么能有沒有起始值的文本框,只是一個空的文本框,我知道零是一個潛在的值,但我只接受大於零的值,所以這對我來說不是問題。
我甚至嘗試將其作為可以為空的十進制進行投射,也嘗試使用非助手(這並不理想),但是,我仍然接收默認的“0”值。 有任何想法嗎??
<%: Html.TextBox("Loan.InterestRate", Model.Loan.InterestRate == 0 ?
(decimal?)null : Model.Loan.InterestRate) %>
在您的模型中添加DisplayFormat屬性
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:#.#}")]
decimal InterestRate { get; set; }
視圖
@Html.TextBoxFor(model => model.InterestRate)
這輸出空而不是0. 這里有更多格式示例
更新
TextBoxFor不適用於格式,但EditorFor可以:
@Html.EditorFor(model => model.InterestRate)
更新2
它適用於TextBoxFor這樣:
@Html.TextBoxFor(model => model.InterestRate, "{0:#.#}")
我使用這個解決方案:
@Html.TextBoxFor(model => model.Year, new { Value = "" })
您可以通過將自定義模板放在/ Shared / EditorTemplates中或通過/ ControllerName / EditorTemplates中的控制器來覆蓋默認模板。
我用這個用於Int。 它的名字叫Int32.ascx:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%@ Import Namespace="System.Web.Mvc.Html" %>
<%
string displayText = string.Empty;
if (Model != null)
{
displayText = Model.ToString();
}
%>
<%= Html.TextBox("", displayText)%>
另一個可能是檢查價值
@Html.TextBoxFor
(m => m.CertificateID, new { @Value = (Model.CertificateID > 0 ?Model.CertificateID.ToString() :string.Empty) })
另一種解決方案是在頁面加載時使用jQuery將空字符串替換為零。 選擇任何名稱作為所有輸入字段的類名,這些字段應填充空字符串而不是零。 例如非零數。
@Html.TextBoxFor(model => model.InterestRate, new { @class = "non-zero-num" })
並在您的頁面上添加以下腳本:
<script>
$(document).ready(function(){
$(".non-zero-num").val($(this).val() == 0 ? '' : $(this).val());
})
</script>
那么“”而不是null。
<%: Html.TextBox("Loan.InterestRate",
Model.Loan.InterestRate == 0 ? "" : Model.Loan.InterestRate) %>
另外為什么不是Loan.InterestRate可以為空?
<%: Html.TextBox("Loan.InterestRate", Model.Loan.InterestRate ?? "") %>
我認為@jfar的答案指向正確的方向,但Int32.ascx應該是這個
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Int32>" %>
<%
string displayText;
if (Model == 0)
{
displayText = "";
}
else
{
displayText = Model.ToString();
}
%>
<%= Html.TextBox("", displayText)%>
或使用Razor更新答案(/Shared/EditorTemplates/Int32.cshtml)
@model Int32
@{
string text = Model == 0 ? "" : Model.ToString();
}
@Html.TextBox("", text)
這是你可以做的:(VB代碼)
這是核心:
@IIf(Model.YourNumericValue = 0, "", Model.YourNumericValue)
以下是使用HTML呈現文本框的方法
<input type="text" name="sYourTextboxName" value="@IIf(Model.YourNumericValue= 0, "", Model.YourNumericValue))">
以下是使用HTML幫助器渲染文本框
@Html.TextBox("sYourTextboxName", IIf(Model.YourNumericValue= 0, "", Model.YourNumericValue))
IIf是一個非常方便的單行功能 - 它的工作方式是這個。
IIf(Expression, TruePart, FalsePart)
所以基本上你說 - 如果我的參數= 0 - 我想什么都不輸出,String.Empty,Null,“” - 而對於假部分 - 它就像 - 哦,如果我的參數不等於0 - 那么必須是除了0以外的東西 - 所以我將輸出我的數值,而不用擔心零將在文本框中。
或者你想要構建它。
希望有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.