How to bind nested objects on HttpPost in ASP.NET

2020-03-31 19:56发布

I have started to implement this solution bind attribute include and exclude property with complex type nested objects

but it does not work at all.

The same question is here Binding nested model with MVC3 on HttpPost

but no concrete answer.

Model

[Bind(Include = "FirstName,MiddleName,LastName,Position,TruckTypeID,Direction,Organization,Objective,TimeStart,TimeEnd")]
public partial class UserRequestRegisterModel
{
    [DisplayName("Имя")]
    [Required]
    public string FirstName { get; set; }

    [DisplayName("Фамилия")]
    [Required]
    public string MiddleName { get; set; }

    [DisplayName("Отчество")]
    [Required]
    public string LastName { get; set; }

    [DisplayName("Должность")]
    [Required]
    public string Position { get; set; }

    [DisplayName("Тип транспорта")]
    [Required]
    public System.Guid TruckTypeID { get; set; }

    [DisplayName("Направление")]
    [Required]
    public string Direction { get; set; }

    [DisplayName("Организация")]
    [Required]
    public string Organization { get; set; }

    [DisplayName("Цель")]
    [Required]
    public string Objective { get; set; }

    [DisplayName("Время убытия")]
    [Required]
    // [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy  HH:mm}", ApplyFormatInEditMode = true)]
    public System.DateTime TimeStart { get; set; }

    [DisplayName("Время прибытия")]
    [Required]
    // [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm}", ApplyFormatInEditMode = true)]
    public Nullable<System.DateTime> TimeEnd { get; set; }        
}


[Bind(Include = "UserRequest")]
public partial class RequestUserModel
{
    public List<UserRequestViewItem> UserRequestViewItems { get; set; }
    public UserRequestRegisterModel UserRequest { get; set; }

    public RequestUserModel()
    {
        UserRequestViewItems = new List<UserRequestViewItem>();
        UserRequest = new UserRequestRegisterModel();
    }
}

Controller

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Bind(Include = "FirstName,MiddleName,LastName,Position,TruckTypeID,Direction,Organization,Objective,TimeStart,TimeEnd")] RequestUserModel userRequest)
//public ActionResult Index(RequestUserModel userRequest)
{
    // !  userRequest.UserRequest is empty  !
    //...
}

1条回答
干净又极端
2楼-- · 2020-03-31 20:38

After 30 minutes of freestyle experimenting I finally get it working.

So, guys, solution is following

Model

 [Bind(Include = "FirstName,MiddleName,LastName,Position,TruckTypeID,Direction,Organization,Objective,TimeStart,TimeEnd")]
    public partial class UserRequestRegisterModel
    {
        [DisplayName("Имя")]
        [Required]
        public string FirstName { get; set; }

        [DisplayName("Фамилия")]
        [Required]
        public string MiddleName { get; set; }

        [DisplayName("Отчество")]
        [Required]
        public string LastName { get; set; }

        [DisplayName("Должность")]
        [Required]
        public string Position { get; set; }

        [DisplayName("Тип транспорта")]
        [Required]
        public System.Guid TruckTypeID { get; set; }

        [DisplayName("Направление")]
        [Required]
        public string Direction { get; set; }

        [DisplayName("Организация")]
        [Required]
        public string Organization { get; set; }

        [DisplayName("Цель")]
        [Required]
        public string Objective { get; set; }

        [DisplayName("Время убытия")]
        [Required]
        // [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy  HH:mm}", ApplyFormatInEditMode = true)]
        public System.DateTime TimeStart { get; set; }

        [DisplayName("Время прибытия")]
        [Required]
        // [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm}", ApplyFormatInEditMode = true)]
        public Nullable<System.DateTime> TimeEnd { get; set; }        
    }


public partial class RequestUserModel
    {
        public List<UserRequestViewItem> UserRequestViewItems { get; set; }
        public UserRequestRegisterModel UserRequest { get; set; }

        public RequestUserModel()
        {
            UserRequestViewItems = new List<UserRequestViewItem>();
            UserRequest = new UserRequestRegisterModel();
        }
    }

HTML

@model TransportRequests.Models.RequestUserModel
...

@using (Html.BeginForm("CreateUserRequest", null, FormMethod.Post, null))
{
   @Html.EditorFor(model => model.UserRequest.FirstName, new { htmlAttributes = new { @class = "form-control", @style = "width:200px" } })
}

Controller

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateUserRequest([Bind(Include = "UserRequest")] RequestUserModel model)
{
     // and here all properties has inputed values... YEAH!!!  :)

     var firstName = model.UserRequest.FirstName;

     return RedirectToAction("Index");
}
查看更多
登录 后发表回答