Set the default value in MVC web application

31,921

Solution 1

The DefaultValue attribute isn't used to set default values on properties like you want. In fact, it isn't directly used by the runtime at all. It's intended instead for use by the Visual Studio designer.

More info here:

http://support.microsoft.com/kb/311339

OR

.Net DefaultValueAttribute on Properties


You can easily set default value of fields in MVC as :

 @Html.EditorFor(model => model.BlockEnd, new { htmlAttributes = new { @class = "form-control", @Value = "499" } })

Now with above code first time when form will loaded initial value of BlockEnd will be 499

Solution 2

I suggest that you create a viewmodel class, and use that to set the default value e.g.

public class ExampleViewModel
{
    public string Slot { get; set; }

    [Required(ErrorMessage = "This field is required")]
    public int BlockStart { get; set; }

    // Include other properties as required.
}

In your controller, make use of the viewmodel like this:

public ActionResult Index()
{
    var viewModel = new ExampleViewModel();
    viewModel.Slot = "A default value";

    return View(viewModel);
}

[HttpPost]
public ActionResult Index(ExampleViewModel viewModel)
{
    // Do whatever you need to do with the values in viewModel e.g. save them to database.
}

Looking at your view code, it seems you wouldn't have to change that, other than putting this at the top

@model ExampleViewModel

I recommend using viewmodels, rather than passing actual data classes, to views since that makes changing view code a lot easier. Also the added flexability you get from using viewmodels is a plus e.g. using a data class, say Car, makes it hard if you also want to display data from another data class, say Driver, on the same view. By using a viewmodel named "VehicleDetailsViewModel" you can have properties such as "DriverName", "CarMake", "CarModel", etc.

EDIT: Ahh, OK so you're using a viewmodel already. In that case, I suggest you set the default values in the constructor of the viewmodel class.

public ExampleViewModel()
{
    this.Slot = "Whatver";
    // etc.
}

I think this is much better than my previous suggestion of setting a default value in the action method above. But you have the choice of selecting where you want to set a default value, it's not set in stone.

I'm not sure if the DefaultValue is actually being picked up by the Razor parser.

Solution 3

Kindly try this:

public partial class RadioRoutingMetadata
{
    public string Slot { get; set; } = "%";

    [Required(ErrorMessage = "This field is requied")]
    public int BlockStart { get; set; } = 0;

    [Required(ErrorMessage = "This field is requied")]
    public int BlockEnd { get; set; } = 499;

    public int FallBackBaseIdentifier { get; set; } = -1;
}
Share:
31,921
Zapnologica
Author by

Zapnologica

I am an enthusiastic developer indulging in the world of programming. in love with C# .net

Updated on July 30, 2020

Comments

  • Zapnologica
    Zapnologica almost 4 years

    I am trying to set the default Value of a field in an ASP.net MVC web application.

    I am using database first so I have added a partial class for meta data as follows:

    [MetadataType(typeof(RadioRoutingMetadata))]
    public partial class RadioRouting
    {
    }
    
    public partial class RadioRoutingMetadata
    {
        [DefaultValue("%")]
        public string Slot { get; set; }
    
        [Required(ErrorMessage = "This field is requied")]
        [DefaultValue(0)]
        public int BlockStart { get; set; }
    
        [Required(ErrorMessage = "This field is requied")]
        [DefaultValue(499)]
        public int BlockEnd { get; set; }
    
        [DefaultValue(-1)]
        public int FallBackBaseIdentifier { get; set; }
    }
    

    No after reading I see that [DefaultValue(T)] doesn't initialise the field to that value when being created. But do the Html helper methods not look at this field?

    here is my view:

    <p>
       @Html.LabelFor(model => model.Slot, htmlAttributes: new { @class = "control-label col-md-2" })
       <span class="field">
           @Html.EditorFor(model => model.Slot, new { htmlAttributes = new { @class = "form-control" } })
           @Html.ValidationMessageFor(model => model.Slot, "", new { @class = "text-danger" })
       </span>
    </p>
    
    <p>
        @Html.LabelFor(model => model.BlockStart, htmlAttributes: new { @class = "control-label col-md-2" })
        <span class="field">
            @Html.EditorFor(model => model.BlockStart, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.BlockStart, "", new { @class = "text-danger" })
        </span>
    </p>
    
    <p>
        @Html.LabelFor(model => model.BlockEnd, htmlAttributes: new { @class = "control-label col-md-2" })
        <span class="field">
            @Html.EditorFor(model => model.BlockEnd, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.BlockEnd, "", new { @class = "text-danger" })
        </span>
    </p>
    

    So When I now provide a Create Form I want these default values to be there in the form.

    Do I have to initialize the Model object in the controller, set the default values, and then pass it through to the create view as if it was an edit view?

    If so how can I create a constructor that initializes all the default values in the partial class?

  • Zapnologica
    Zapnologica almost 10 years
    I am making use if a ViewModel Right now, It just happens to be that my View models is the same as my Database Model.
  • Zapnologica
    Zapnologica almost 10 years
    So In other words, I shouldn't ever really use it?
  • Kartikeya Khosla
    Kartikeya Khosla almost 10 years
    @Zapnologica...Yes..in order to fulfill your requirement you have to do something else...
  • Kartikeya Khosla
    Kartikeya Khosla almost 10 years
    @Zapnologica..if you want to fill your form with some default values then above answer could work or you can use "@Value" html attribute to set default values..
  • Zapnologica
    Zapnologica almost 10 years
    Thanks, That is a nice to know I will remember it. However I would prefer a More central solution where I only apply the default Value ONCE. However I do have some situations where that will come in handy. Thanks. Wish the helper methods could look at a metadata attribute and add the @Value
  • Kartikeya Khosla
    Kartikeya Khosla almost 10 years
    @Zapnologica...visit these links...stackoverflow.com/questions/7637022/… and this also..stackoverflow.com/questions/16561889/…
  • Crismogram
    Crismogram over 9 years
    I really like the last example but think you forgot the parenthesis. <br>