提交表单后,模型中的对象列表为空

时间:2019-03-03 15:15:17

标签: c# asp.net-mvc

在cshtml文件中,我遍历带有对象的列表,并将值绑定到文本框。这是我的部分看法。

@model BotelHotel.Models.ViewModels.BookingViewModel
<div>
    @using (Html.BeginForm("StepThree", "Book", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {

        @Html.LabelFor(model => model.BookingDate)<br />
        @Html.TextBoxFor(model => model.BookingDate, new { @class = "form-control datepicker", placeholder = "Datum Boeking", @readonly = true })

        @Html.LabelFor(model => model.AmountOfPersons)<br />
        @Html.TextBoxFor(model => model.AmountOfPersons, new { @class = "form-control", @readonly = true })<br />

        for (int i = 0; i < Model.persons.Count; i++)
        {
            @Html.LabelFor(model => model.persons[i].Name)<br />
            @Html.TextBoxFor(model => model.persons[i].Name, new { @class = "form-control"})<br />
        }

        <button class="btn btn-success">Submit</button>
    }
</div>

单击提交按钮后,我在StepThree函数上有一个断点。列表persons为空。有什么理由为什么它是空的?其余的stackoverflow似乎都说这是一个很好的解决方案。但这对我不起作用。

这是我的模特。

public class BookingViewModel
    {
        public string step { get; set; }
        public int roomID { get; set; }
        public List<PersonViewModel> persons = new List<PersonViewModel>();

        public BookingViewModel()
        {

        }

        public BookingViewModel(int roomID)
        {
            this.roomID = roomID;
            this.step = "PartialOne";
        }

        [Required]
        [DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
        [Display(Name = "Datum")]
        public DateTime BookingDate { get; set; }

        [Required]
        [Display(Name = "Aantal personen")]
        public int AmountOfPersons { get; set; }

    }
public class PersonViewModel
    {

        private Person _person;

        public PersonViewModel()
        {
            _person = new Person();
        }

        public PersonViewModel(Person person)
        {
            _person = person;
        }


        public int Id { get; set; }
        [Required]
        [Display(Name = "Naam")]
        public string Name { get; set; }
        [Required]
        [Display(Name = "Adres")]
        public string Address { get; set; }
        [Required]
        [Display(Name = "Email")]
        public string Email { get; set; }
        [Required]
        [Display(Name = "Post Code")]
        public string Postal_code { get; set; }

    }

以及要发布到的方法

        public ViewResult StepThree(BookingViewModel model)
        {
            model.step = "PartialThree";
            return View("Book", model);
        }

1 个答案:

答案 0 :(得分:1)

尝试将其更改为属性而不是字段:

public List<PersonViewModel> persons {get;set;}

并从构造函数初始化它:

persons = new List<PersonViewModel>();