@Html.TextBoxFor not display a specific value

1k views Asked by At

I'm developing a website in ASP .Net with Razor.

For my forms i'm using Helpers (like @Html.TextBoxFor) and i'd like NOT to show a specific value. It's tricky to explain, so here's some code.

My model

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

My view

@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>
}

So, of course, my input here has a value of -1, and, because i'm using this partial even in some other views, where the WorkCenterNumber is different than -1.

So, i'd like to display the WorkCenterNumber only when it's different than -1.

It may seem a bit stupid, but i hope there is someting in the helpers that'll allow me to do this.

Thanks !

EDIT: Additional random information added via a comment: "SearchedInstruction is a model from a custom framework of my company, so i'm not allowed to change this

2

There are 2 answers

2
fdomn-m On BEST ANSWER

Don't use magic numbers.

Here it appears you're using -1 to mean not-yet-specified-by-the-user, but maybe not, that's why you don't use numbers for meaning.

In this case, I'd change the int to a nullable int then the default value will be null and the textbox will be empty on first load.

Edit: Additional random information added via a comment: "SearchedInstruction is a model from a custom framework of my company, so i'm not allowed to change this".

In which case, add a new ViewModel for your view and map the values across (eg using AutoMapper or anything similar)

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

Change your view to use this viewmodel

@model SearchedInstructionViewModel

and populate in the controller

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);
3
hutchonoid On

Simply change your get to the following which does the logic:

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