在一个asp.net mvc的视图模型默认值 [英] Default value in an asp.net mvc view model

查看:434
本文介绍了在一个asp.net mvc的视图模型默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的模型:

 公共类SearchModel
{
    [默认值(真)
    公共BOOL IsMale {搞定;组; }
    [默认值(真)
    公共BOOL IsFemale {搞定;组; }
}

但基于我的研究和答案在这里, DefaultValueAttribute 实际上并没有设置默认值。但是,这些答案是从2008年,是否有一个属性或比使用私有字段传递给视图时设置这些值来真正的更好的办法?

继承人的看法反正:

  @using(Html.BeginForm(搜索,用户,FormMethod.Get))
{
< D​​IV>
    @ Html.LabelFor(M = GT; Model.IsMale)
    @ Html.CheckBoxFor(M = GT; Model.IsMale)
    <输入类型=提交值=搜索/>
< / DIV>
}


解决方案

此设置在构造函数中:

 公共类SearchModel
{
    公共BOOL IsMale {搞定;组; }
    公共BOOL IsFemale {搞定;组; }    公共SearchModel()
    {
        IsMale = TRUE;
        IsFemale = TRUE;
    }
}

然后将它传递给视图中的GET操作:

  [HTTPGET]
公众的ActionResult搜索()
{
    返回新景(新SearchModel());
}

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>
}

解决方案

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());
}

这篇关于在一个asp.net mvc的视图模型默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆