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

本文关键字:模型 我的 填充 我可以 | 更新日期: 2023-09-27 18:31:49

这是我的所有模型类

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

特别看到这个代码....它是否有效,因为我现在不在电脑之前。

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

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

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

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

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

它应该是这样的:

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