MVC3默认值 [英] mvc3 default values

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

问题描述

我如何定义一个模型属性的默认值?
属性默认值不工作:

  [DisplayName的(相关信息)]
    [默认值(测试)]
    [数据类型(DataType.MultilineText)
    公共对象的相关信息{搞定;组; }


解决方案

不是用来做什么的,你认为它是默认值。

从<一个href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx\">DefaultValueAttribute MSDN页面


  

您可以创建任意值DefaultValueAttribute。成员的默认值通常是其初始值。可视化设计器可以使用默认值重置成员的价值。 code发生器可以使用默认值也以确定是否code应为会员产生。


  
  

注:DefaultValueAttribute不会造成一名成员与属性的值自动初始化。您必须在code设置的初始值。


为什么不直接设置在构造函数的默认设置为你的模型?

 公共类为MyModel {
    公众为MyModel(){相关信息=测试; }    [显示名称(相关信息)]
    [数据类型(DataType.MultilineText)
    公共ojbect的相关信息{搞定;组; }
}

编辑:

因为你似乎使用EF模型是,你想设置的默认值。您只需创建一个部分类的构造函数。

 公共部分类myEntity所{
    公共myEntity所(){相关信息=测试; }
}

How can i define the default value for a model property? The attribute DefaultValue is not working:

    [DisplayName("Infos")]
    [DefaultValue("Test")]
    [DataType(DataType.MultilineText)]
    public object infos { get; set; }

解决方案

DefaultValue is not used for what you think it is.

From the DefaultValueAttribute MSDN page

You can create a DefaultValueAttribute with any value. A member's default value is typically its initial value. A visual designer can use the default value to reset the member's value. Code generators can use the default values also to determine whether code should be generated for the member.

Note: A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.

Why not just set the defaults in a constructor for your Model?

public class MyModel {
    public MyModel() { infos = "Test"; }

    [DisplayName("Infos")]
    [DataType(DataType.MultilineText)]
    public ojbect infos { get; set; }
}

EDIT:

Since you seem to be using EF models and you want to set a default value. You just create a partial class with a constructor.

public partial class MyEntity {
    public MyEntity() { infos = "Test"; }
}

这篇关于MVC3默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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