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> }
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.
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.
A member's default value is typically its initial value. A visual designer can use the default value to reset the member's value.
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()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With