asp.net-mvc asp.net mvc 视图模型中的默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7637022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:30:20  来源:igfitidea点击:

Default value in an asp.net mvc view model

asp.net-mvcasp.net-mvc-3

提问by Shawn Mclean

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, DefaultValueAttributedoes 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?

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

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

回答by Dismissile

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:

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

[HttpGet]
public ActionResult Search()
{
    return new View(new SearchModel());
}

回答by Guruprakash

Use specific value:

使用特定值:

[Display(Name = "Date")]
public DateTime EntryDate {get; set;} = DateTime.Now;//by C# v6

回答by CodeGrue

Create a base class for your ViewModelswith the following constructor code which will apply the DefaultValueAttributeswhen any inheriting model is created.

ViewModels使用以下构造函数代码为您创建一个基类,该代码将在DefaultValueAttributes创建任何继承模型时应用。

public abstract class BaseViewModel
{
    protected BaseViewModel()
    {
        // apply any DefaultValueAttribute settings to their properties
        var propertyInfos = this.GetType().GetProperties();
        foreach (var propertyInfo in propertyInfos)
        {
            var attributes = propertyInfo.GetCustomAttributes(typeof(DefaultValueAttribute), true);
            if (attributes.Any())
            {
                var attribute = (DefaultValueAttribute) attributes[0];
                propertyInfo.SetValue(this, attribute.Value, null);
            }
        }
    }
}

And inherit from this in your ViewModels:

并在您的 ViewModel 中继承它:

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

回答by Oleksii Aza

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

如果您需要将相同的模型发布到服务器,那么bool在构造函数中具有默认值的解决方案对您来说是不可行的。假设您有以下模型:

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).

问题是当用户取消选中此复选框并将其发布到服务器时 - 您最终会在构造函数中设置默认值(在这种情况下为 true)。

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

所以在这种情况下,我最终只会在视图中指定默认值:

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

回答by Oleksii Aza

What will you have? You'll probably end up with a default search and a search that you load from somewhere. Default search requires a default constructor, so make one like Dismissile has already suggested.

你会有什么?您可能会以默认搜索和从某处加载的搜索结束。默认搜索需要一个默认构造函数,所以像 Dismissile 已经建议的那样制作一个。

If you load the search criteria from elsewhere, then you should probably have some mapping logic.

如果您从其他地方加载搜索条件,那么您可能应该有一些映射逻辑。