Click here to Skip to main content
15,883,797 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
What is the best way to deal with default values in Entity Framework code first? I am using ASP.NET MVC 4 for the first time and the views dont show all the input fields, but some values like a timestamp and the user who entered the record need to be defaulted.

Also, for editing and updates how can I allow the user to edit data in a view that only shows editable fields and not set the default values to null when saved. The date from before seems to be set to null since it is not shown on the view. I thought maybe it would work to have hidden fields, but is there a better way?
Posted

1 solution

Let's assume, you are dealing with a "person" entity in mvc. Think about the data flow when you use a "create" scaffold: when you call the NewPerson action (the HttpGet edition of it), you will probably just make a simple return View();. Ok, the view is rendered, and you get the html code. Yes, the view is referencing the model, but it is only reflected, you don't have a model object, just the model type. Of course, there could be a DefaultValue[^] attribute for that, but it's for something else. It could be used by the helper, but it is not.
Well, you still don't know what to do...
Ok, remember what you are usually doing in the HttpPost version of the NewPerson action. You get the model populated with an instance, you validate it, and if the validation fails, you pass the model object to the same view. And wow, you the rendered html will have the values. Well, why don't use the same concept in the HttpGet version as well?
So: simply create a model object, fill it with the default values. Of course you can add a constructor to the model class and set these values there. (You could add default values, if you would use public fields instead of public properties, but I suggest you don't). And pass this newly created object filled with the defaults to the view.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900