@Html.TextBoxFor 不显示特定值

@Html.TextBoxFor not display a specific value

我正在使用 Razor 在 ASP.Net 中开发一个网站。

对于我的表单,我正在使用帮助程序(如 @Html.TextBoxFor)并且我不想显示特定值。很难解释,所以这里有一些代码。

我的模型

public class SearchedInstruction
{
    private int _workCenterNumber= -1;
    public int WorkCenterNumber
    {
        get { return _idWorkCenter; }
        set { _idWorkCenter = value; }
    }
}

我的观点

@model InstructionSearchViewModel

@using (Html.BeginForm("InstructionSearch", "Search", FormMethod.Post, new { onsubmit = "submitSearchInstruction()" }))
{
    <div class="col-md-3">
        @Html.Label("Poste de charge")
        @Html.TextBoxFor(m => m.WorkCenterNumber, new { @class = "form-control" })
    </div>
}

所以,当然,我这里的 input 的值为 -1,而且,因为我什至在其他一些视图中也使用了这个部分,其中 WorkCenterNumber 是不同于 -1.

所以,我想仅在 WorkCenterNumber 不同于 -1 时才显示它。

这可能看起来有点愚蠢,但我希望助手中有一些东西可以让我这样做。

谢谢!

编辑: 通过评论添加的附加随机信息:“SearchedInstruction 是我公司自定义框架的模型,因此我不能更改它

只需将您的 get 更改为执行逻辑的以下内容:

public class SearchedInstruction
{
    private int _idWorkCenter = -1;
    public string IdWorkCenter
    {
        get { return _idWorkCenter != -1 ? _idWorkCenter : string.Empty; }
        set { _idWorkCenter = value; }
    }
}

不要使用 magic numbers

这里您似乎使用 -1 来表示用户尚未指定,但也许不是,这就是为什么您不使用数字表示含义的原因。

在这种情况下,我会将 int 更改为 nullable int,然后默认值将为 null,并且文本框在第一次加载时将为空。

编辑:通过评论添加的额外随机信息:"SearchedInstruction is a model from a custom framework of my company, so i'm not allowed to change this"。

在这种情况下,为您的视图添加一个新的 ViewModel 并映射值(例如使用 AutoMapper 或类似的东西)

public class SearchedInstructionViewModel
{
    public int? IdWorkCenter { get;set; }
}

更改视图以使用此视图模型

@model SearchedInstructionViewModel

并填充到控制器中

var model = db.SearchedInstruction.Load...  // however you load the *model*
var viewModel = new SearchedInstructionViewModel();
viewModel.IdWorkCenter = model.IdWorkCenter;
// etc, or use an automapper

return View(viewModel);