5

MVC @Html.TextBoxFor(model => model.SomeNotNullableType) When using this helper, if I have a type that is not nullable in the database the view ends up with a default value in the text box. Specifically in my case, the field takes an integer, and it's putting a default value of 0 in the field.

I know I could remove the erroneous 0 with Javascript or setting the default value in html, but I was hoping there was a more 'correct' way of doing this. Can I specify in my model that I don't want a default view to be put into the text box (you cannot set it to null, as it is not nullable). Sticking with the true model approach I'd like to fix it in the model/controller, rather than in the view.

Community
  • 1
  • 1
petebowden
  • 900
  • 2
  • 8
  • 21

2 Answers2

3

perhaps adding a viewmodel for that model class with a nullable int property (and all other properties for that class), and then using data annotations to make it a required field would serve the purpose you're looking for.

you would then just need to roll the viewmodel back into your data persistence class in your controller.

nathan gonzalez
  • 11,817
  • 4
  • 41
  • 57
  • I agree this is probably the best way to go, but I wish I wouldn't need to create "helper" viewmodels for every model that has a nullable type. – petebowden Nov 01 '11 at 20:07
  • well, theoretically you shouldn't be passing around persistence objects in the first place, so you'd always need some kind of intermediate class between display layer and data layer. – nathan gonzalez Nov 01 '11 at 20:33
  • well I was going to answer the same thing but got asked a question by a co-worker and you beat me to it! Great job. – Michael Brown Nov 01 '11 at 20:35
  • @nathan : Can you clarify what you mean by "persistence objects"? I'm using the repository pattern and have passed the entities as a model to a view. Should I be creating a separate viewmodel for each repository model? Do you have an example of why my following this practice is bad? – Rastapopulous 6 mins ago – petebowden Nov 01 '11 at 20:55
  • @Rastapopulous, objects supplied by your orm, if you're using one. most orm's put a proxy on top of your class, and then you interact with that proxy object. by passing that object into the view you're passing an object that has more information (persistence, state, etc) than your view needs. if your repository returns objects that do not originate from an orm, than the point is invalid, as the translation from the proxy objects has already happened. – nathan gonzalez Nov 01 '11 at 22:41
0

You could create a custom editor (partial view) for the int type in which you create the textbox and you can set the value to when it's the default value.