Setting default value for @Html.EditorFor in asp.net mvc

Yesterday one of my friend asked me to set default value for @HTML.EditorFor. So I decided to write this blog post. In this blog post I am going to Explain How we create Default values for model Entities. So Let’s start this via taking a simple example Model class called User. In User Model class I have created two properties UserName and UserJoinedDate. Following is a code for that.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CodeSimplified.Models
{
    public class User
    {
        private DateTime _userJoinDate = DateTime.Now;

        public DateTime UserJoinDate
        {
            get
            {
                return _userJoinDate;
            }
            set
            {
                _userJoinDate = value;
            }
        }

        public string UserName
        { get; set; }
    }
}
As you can see in above class username is default property while for UserJoinedDate I have used old method of declaring properties. Where I have assigned a private variable with System DateTime.

Now let’s Create a Action Result User in Home Controller like following where I am returning a new User View like following.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CodeSimplified.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult User()
        { return View(new CodeSimplified.Models.User()); }
    }
}

Now Let’s Create User View from the action  right click Add view like following. Here I have created Strongly Typed view like following.

User

Once you click Add It will add a new View like following.

@model CodeSimplified.Models.User

@{
    ViewBag.Title = "User";
}

<h2>User</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>User</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.UserJoinDate)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.UserJoinDate)
            @Html.ValidationMessageFor(model => model.UserJoinDate)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.UserName)
        </div>
        <div class="editor-field">
            @Html.te
            @Html.EditorFor(model => model.UserName)
            @Html.ValidationMessageFor(model => model.UserName)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

Now everything is ready so Let's run that in browser. Following is the output as expected.

Browser 

So that’s it. It’s very easy. Hope you liked it. Stay tuned for more.. Till then happy programming.

Shout it
Published Tuesday, August 16, 2011 2:15 AM by Jalpesh P. Vadgama
Filed under: ,

Comments

# Setting default value for @Html.EditorFor in... | ASP.NET and ASP.NET MVC | Syngu

Pingback from  Setting default value for @Html.EditorFor in... | ASP.NET and ASP.NET MVC | Syngu

# re: Setting default value for @Html.EditorFor in asp.net mvc

Wednesday, September 07, 2011 6:19 PM by Pat

What if you have two places to use the same object and wanted a different value as the default?

Say you are entering products with an expiration date. Adding a milk product would default to something sooner than if you were adding a canned good product.

# re: Setting default value for @Html.EditorFor in asp.net mvc

Thursday, September 08, 2011 7:17 AM by Jalpesh P. Vadgama

@Pat- This was a simple example. But You can use constructor of class to assign this default value. For example

public class User

   {

       public User(DateTime userJoinDate)

       {

            this._userJoinDate=userJoinDate;

       }

       private DateTime _userJoinDate;

       public DateTime UserJoinDate

       {

           get

           {

               return _userJoinDate;

           }

           set

           {

               _userJoinDate = value;

           }

       }

       public string UserName

       { get; set; }

   }

so when you create new object of user model class you can pass your datetime value of your choice.

# re: Setting default value for @Html.EditorFor in asp.net mvc

Thursday, September 08, 2011 11:07 AM by Pat

As silly as it sounds, what I wanted to do was set the default value in the control using Razor trying something like @Html.EditorFor(model => model.Expiration, new { value = "1/1/2012" }). It did not work.

You just need to set the value in the model to whatever you want and pass it to the view. Your overloaded constructor works, or you can just set the value manually.

public ActionResult User(){ return View(new CodeSimplified.Models.User(DateTime.Parse("1/1/2012"))); }

OR

public ActionResult User(){ var user = new User(); user.JoinDate = DateTime.Parse("1/1/2012"); return View(user); }