Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value in an asp.net mvc view model

I have this model:

public class SearchModel {     [DefaultValue(true)]     public bool IsMale { get; set; }     [DefaultValue(true)]     public bool IsFemale { get; set; } } 

But based on my research and answers here, DefaultValueAttribute does not actually set a default value. But those answers were from 2008, Is there an attribute or a better way than using a private field to set these values to true when passed to the view?

Heres the view anyways:

@using (Html.BeginForm("Search", "Users", FormMethod.Get)) { <div>     @Html.LabelFor(m => Model.IsMale)     @Html.CheckBoxFor(m => Model.IsMale)     <input type="submit" value="search"/> </div> } 
like image 501
Shawn Mclean Avatar asked Oct 03 '11 15:10

Shawn Mclean


People also ask

Can we set default value for model?

In practice, you could create the ViewModel, and override these defaults with values pulled from a database entry (using the data-backed model), but as-is, this will always use these default values.

What is default URL in MVC?

As you can see in the above figure, the route is configured using the MapRoute() extension method of RouteCollection , where name is "Default", url pattern is "{controller}/{action}/{id}" and defaults parameter for controller, action method and id parameter.

What is the default value of the attribute?

A member's default value is typically its initial value. A visual designer can use the default value to reset the member's value.


1 Answers

Set this in the constructor:

public class SearchModel {     public bool IsMale { get; set; }     public bool IsFemale { get; set; }      public SearchModel()     {          IsMale = true;         IsFemale = true;     } } 

Then pass it to the view in your GET action:

[HttpGet] public ActionResult Search() {     return new View(new SearchModel()); } 
like image 82
Dismissile Avatar answered Oct 18 '22 19:10

Dismissile