Default value in an asp.net mvc view model

后端 未结 6 564
星月不相逢
星月不相逢 2020-12-05 01:37

I have this model:

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


        
6条回答
  •  -上瘾入骨i
    2020-12-05 01:53

    In case you need to post the same model to server the solution with having default bool value in constructor would not be viable for you. Let's imagine that you have following model:

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

    On view you would have something like this:

    @Html.CheckBoxFor(n => n.IsMale)
    

    The problem is when user uncheck this checkbox and post it to the server - you would end up with default value set up in constructor (which in this case is true).

    So in this case I would end up with just specifying default value on view:

    @Html.CheckBoxFor(n => n.IsMale, new { @checked = "checked" })
    

提交回复
热议问题