I'm using Entity Framework to create my data objects. I have an entity called Users.开发者_StackOverflow It contains a property named Code, which is an integer.
The problem is that when I pass a blank User entity to my Create view, and call
<%: Html.TextBoxFor(m => m.Code) %>
the textbox is populated with a 0.
I can't set the property to nullable because the value can't be null in my database. Which means I can't set the value to null in my controller.
What do I do?
You shouldn't be binding directly to an EF model, exactly for these types of issues.
EF shouldn't care about UI, and the UI shouldn't care about EF.
The recommended middle-man is always a ViewModel.
Setup a ViewModel in your Controller, which should contain a string property for the code, which you can bind to (like @Divi says).
When you submit the form, map the ViewModel to the EF model in order to persist to the database.
Couldn't you create a string property on the model and bind the view to that? And in the controller set the actual int property based on the string property?
精彩评论