Steven
Steven

Reputation: 18859

Set initial value for model property?

I'm using Entity Framework to create my data objects. I have an entity called Users. 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?

Upvotes: 0

Views: 204

Answers (2)

RPM1984
RPM1984

Reputation: 73112

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.

Upvotes: 4

Divi
Divi

Reputation: 7691

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?

Upvotes: 0

Related Questions