我可以这样填充我的模型c#

时间:2013-09-17 14:07:39

标签: c#

这是我的所有模型类

public class Student
    {
        [Required(ErrorMessage = "First Name Required")] // textboxes will show
        [Display(Name = "First Name :")]
        [StringLength(5, ErrorMessage = "First Name cannot be longer than 5 characters.")]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "Last Name Required")] // textboxes will show
        [Display(Name = "Last Name :")]
        [StringLength(5, ErrorMessage = "Last Name cannot be longer than 5 characters.")]
        public string LastName { get; set; }

        [Required(ErrorMessage = "DOB require")] // datepicker will show
        [Display(Name = "DOB :")]
        [DataType(DataType.Date)]
        public DateTime Dob { get; set; }

        [Required(ErrorMessage = "State Required")] // drodown will show
        [Display(Name = "State :")]
        public List<State> State { get; set; }

        [Required(ErrorMessage = "City Required")] // drodown will show
        [Display(Name = "City :")]
        public List<City> City { get; set; }

        [Required(ErrorMessage = "Language known Required")] // group of checkboxes will show
        [Display(Name = "Language known :")]
        public List<Language> Language { get; set; }

        [Required(ErrorMessage = "Sex Required")] // group of radio button will show
        [Display(Name = "Sex :")]
        public List<Sex> Sex { get; set; }

        [Required(ErrorMessage = "Computer Course Required")] // listbox will show
        [Display(Name = "Computer Course Done :")]
        public List<ComputerCourse> ComputerCourse { get; set; }

    }

我可以这样填充吗?

var model =  new Student()
{
    FirstName = "John",
    LastName = "Doe",
    Dob = DateTime.Now,

    State = new list<State>()
        {
            new state({ID="1" , Name = "test1"});
            new state({ID="2" , Name = "test2"});
            new state({ID="3" , Name = "test3"});
        };

}

特别看到这个代码....它是否有效bcoz我现在不在我的电脑前。

State = new list<State>()
            {
                new state({ID="1" , Name = "test1"});
                new state({ID="2" , Name = "test2"});
                new state({ID="3" , Name = "test3"});
            };

请告诉我是否需要编辑或更改模型填充代码的任何区域。感谢

2 个答案:

答案 0 :(得分:2)

当你以这种方式提供参数时,你可以省略空括号......

var model =  new Student //deleted parenthesis
{
    FirstName = "John",
    LastName = "Doe",
    Dob = DateTime.Now,    
    State = new List<State>//deleted parenthesis
        {
//          new State({ID="1" , Name = "test1"}); don't wrap params in parenthesis
            new State{ID="1" , Name = "test1"},
            new State{ID="2" , Name = "test2"},
            new State{ID="3" , Name = "test3"}
        }    
}

答案 1 :(得分:1)

应该是这样的:

State = new List<State>
            {
                new State{ID="1" , Name = "test1"},
                new State{ID="2" , Name = "test2"},
                new State{ID="3" , Name = "test3"}
            }