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

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

问题描述

我有这个模型:

公共类 SearchModel{[默认值(真)]public bool IsMale { get;放;}[默认值(真)]public bool IsFemale { get;放;}}

但根据我在这里的研究和回答,DefaultValueAttribute 实际上并没有设置默认值.但这些答案来自 2008 年,当传递给视图时,是否有属性或比使用私有字段将这些值设置为 true 更好的方法?

这里是视图:

@using (Html.BeginForm("Search", "Users", FormMethod.Get)){<div>@Html.LabelFor(m => Model.IsMale)@Html.CheckBoxFor(m => Model.IsMale)<input type="submit" value="search"/>

}

解决方案

在构造函数中设置:

公共类 SearchModel{public bool IsMale { get;放;}public bool IsFemale { get;放;}公共搜索模型(){IsMale = 真;IsFemale = true;}}

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

[HttpGet]公共操作结果搜索(){返回新视图(新搜索模型());}

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天全站免登陆