首页 > 解决方案 > 如何清除使用脚手架创建视图时创建的 EditorFor 输入元素。

问题描述

我创建了一个这样的视图模型:

public class M_Master
{
    public string SUPWH { get; set; }

    public string STKGL { get; set; }

    public string SALGL { get; set; }

    public string COSGL { get; set; }


    public decimal ROQ { get; set; }

    public int MIN { get; set; }

    public int MAX { get; set; }

    public int LT { get; set; }

    public string PRODSPEC { get; set; }

    public string REMK1 { get; set; }

    public string REMK2 { get; set; }

    public decimal openingQty { get; set; }
    public decimal openingAmt { get; set; }
    public decimal onHandQty { get; set; }
    public decimal ytdReceiptQty { get; set; }

}

然后我使用这个 ViewModel 来创建一个 View。所以视图看起来像下面这样:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>INV_Master</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.PROD, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PROD, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PROD, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.WH, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.WH, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.WH, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.DESCR, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.DESCR, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.DESCR, "", new { @class = "text-danger" })
            </div>
        </div>

我意识到的是,当我访问页面/视图时,input默认情况下,html 字段会填充为 ViewMoel 中的那些属性的值,例如 0,这些属性是 int、decimal、datetime。如何确保input默认情况下所有字段为空?

标签: c#asp.net-mvcrazor

解决方案


使用可空类型,如 int?、decimal? 和 DateTime?。当对象被实例化时,每个属性都会被初始化为默认的数据类型。int 默认为 0,而 int? 默认为空。等等。您仍然可以在属性上放置 [Required] 以确保它们在被回发到服务器之前由用户输入。


推荐阅读