Click here to Skip to main content
13,351,156 members (24,900 online)
Rate this:
Please Sign up or sign in to vote.
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 13-Dec-12 8:57am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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.

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web02 | 2.8.180111.1 | Last Updated 13 Dec 2012
Copyright © CodeProject, 1999-2018
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100