Search code examples
asp.net-mvcasp.net-mvc-5default-value

Set the default value in MVC web application


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?


Solution

  • 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