对于整数/小数Html.TextboxFor默认值是空的,而不是0小数、整数、默认值、而不是

2023-09-04 22:39:55 作者:超人不会飞

我使用的是默认的asp.net MVC 2语法来构建文本框的哪个是整数或小数点我的asp.net MVC的Web应用程序:

I am using the default asp.net MVC 2 syntax to construct TextBox's which are integer or decimal for my asp.net MVC web app:

<%: Html.TextBoxFor(model => model.Loan.InterestRate) %>

pretty的直线前进,但问题是固有的事实,我结合模型对象是十进制或int和非空的,他们打印他们的值为零(0),在页面加载,如果我的模型是空的(如在添加模式的CRUD模板)和零是一个不正确的值,是我的网页验证也无效。

pretty straight forward, but the problem is inherently of the fact my binding model objects are decimal or int and non-nullable, they print their value as zero (0) on page load if my model is empty (such as in add mode for a CRUD template) and zero is an incorrect value and is invalid for my page validation also.

我怎么能有这没有初始值,只是一个空洞的文本框的文本框,我知道零是一个潜在的价值,但我只接受值大于零,无论如何,所以这不是我的问题。

How could I have textboxes which have no starting value, just an empty textbox, I understand zero is a potential value, but I only accept values greater than zero anyway, so this is not a problem for me.

我甚至尝试铸造为一个不能为空小数,也非用于帮助(这是不理想的),但很可惜,我还是接受默认的0值。任何想法??

I even tried casting as a nullable decimal and also a non-for helper (which is not ideal), but alas, I am still receiving the default '0' value. any ideas??

<%: Html.TextBox("Loan.InterestRate", Model.Loan.InterestRate == 0 ? 
    (decimal?)null : Model.Loan.InterestRate) %>

感谢。

推荐答案

您可以通过将一个自定义的模板/共享/ EditorTemplates或控制器/ ControllerName / EditorTemplates覆盖默认的模板。

You can override the default template by putting a custom template in /Shared/EditorTemplates or by controller in /ControllerName/EditorTemplates.

我用这一个诠释的。它的命名Int32.ascx:

I use this one for Int's. Its named 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)%>