The easiest way is to initialize the properties in the model constructor:
public class PersonModel { public PersonModel () { FirstName = "Default first name"; Description = "Default description"; } public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Description { get; set; } }
And when you want to send it to a view, for example, in PersonController.Create action-method:
public ActionResult Create() { var model = new PersonModel(); return View(model); } [HttpPost] public ActionResult Create(PersonModel model) { // do something on post-back }
That's all. Remember that you need to create a new instance of your model and pass it to the view in order to use its default values. Since the view associated with this action method expects an instance of PersonModel , but when you use the create method as follows:
public ActionResult Create() { return View(); }
the view got nothing (I mean null ), so your default values ββdo not exist.
But if you want to do this for complex purposes, for example. using the default value as a watermark, or as @JTMon said you don't want end users to see the default values, you will have other solutions. Please let me know your purpose.
javad amiry
source share