Razor 在@Html.textbox中为MVC Core 2设置默认值
我有一个文本框,在初始页面加载(并假设为空模型)时,html TextBoxFor helper将用0填充文本框。由于0是一个值,我想将此行为更改为“”(null、nothing等)。考虑到关于这方面的大量文献,我认为这应该是直截了当的;然而,我不能让它工作。这是我得到的(我已经把它解析得很简单,请原谅我的错误) 型号:Razor 在@Html.textbox中为MVC Core 2设置默认值,razor,asp.net-core-mvc,Razor,Asp.net Core Mvc,我有一个文本框,在初始页面加载(并假设为空模型)时,html TextBoxFor helper将用0填充文本框。由于0是一个值,我想将此行为更改为“”(null、nothing等)。考虑到关于这方面的大量文献,我认为这应该是直截了当的;然而,我不能让它工作。这是我得到的(我已经把它解析得很简单,请原谅我的错误) 型号: public class Something_ViewModel { [DisplayName("Feet:")] public int Feet{ get; set;
public class Something_ViewModel
{ [DisplayName("Feet:")]
public int Feet{ get; set; }
}
控制器:
public IActionResult RetainedOwnership()
{
Models.Analytics.Something_ViewModel RO_VM = new Models.Analytics.Something_ViewModel();
Return View(RO_VM);
}
我试过的标签助手:
@Html.TextBoxFor(Model => Model.Feet, new { id = "txtFeet", @Value = Model.Feet.ToString() ?? "" })
@Html.TextBoxFor(Model => Model.Feet, new { id = "txtFeet", Value = Model.Feet.ToString() ?? "" })
@Html.TextBoxFor(Model => Model.Feet, new { id = "txtFeet", Value = "" })
@Html.TextBoxFor(Model => Model.Feet, new {Value = "" })
@Html.TextBoxFor(Model => Model.Feet, new {@Value = "" })
@Html.TextBoxFor(Model => Model.Feet, new {id = "txtFeet"})
您可能需要将
Feet
数据类型更改为int?
。默认值为空 成功了。对于其他人,这就是我发现的——int、decimal、float等。默认情况下,值类型是必需的,不可为null。如果希望它可以为null,则必须执行以下操作:System.nullable或其缩写为int。在任何情况下,在使用HtmlHelper
方法时,都不应设置value
属性