Click here to Skip to main content
Rate this: bad
good
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 7:57am

1 solution

Rate this: bad
good
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.
  Permalink  

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

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 Guruprasad.K.Basavaraju 450
1 Sergey Alexandrovich Kryukov 370
2 Shai Vashdi 318
3 OriginalGriff 265
4 Peter Leow 171
0 Sergey Alexandrovich Kryukov 9,109
1 OriginalGriff 5,290
2 Peter Leow 4,010
3 Maciej Los 3,535
4 Abhinav S 3,263


Advertise | Privacy | Mobile
Web03 | 2.8.140415.2 | Last Updated 13 Dec 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Use
Layout: fixed | fluid