I have created a ParentModel because i want to use two models inside this so that i can use the same in view in MVC.

When i get the data on initial load both properties defined in Parent model populate properly. However, when i try to add new data i see second property as null. Here is my code :

public class UserModel
{
public User User { get; set; }        
public IEnumerable<RolesModel> rolesModel { get; set; }
}

[HttpPost]
        [ValidateAntiForgeryToken()]
        public ActionResult Add(UserModel userDetails)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    userDetails.User.FullName = userDetails.User.FirstName + " " +          userDetails.User.MiddleName + " " + userDetails.User.LastName;
                    userDetails.User.CreatedDate = DateTime.Now;
            _userService.Insert(userDetails.User);
                   _unitOfWorkAsync.SaveChanges();
foreach (RolesModel rolesModel in userDetails.rolesModel)
{
//Here userdetails.rolesmodel is null
}
}

View :

@model Axp.Gcst.Gps.Web.Areas.Admin.Models.UserModel
@using (Html.BeginForm("Add", "user", FormMethod.Post, new { @class = "form-horizontal" }))
{


    @Html.AntiForgeryToken()

    @Html.Partial("_UserDetails", Model)

                                @foreach (var itemRole in Model.rolesModel)
                                {

                                    if (itemRole.Role.RoleGroupId == item.RoleGroupId)
                                    {
                                        <div class="col-md-12 col-sm-12 col-xs-12 panel_cell">@Html.CheckBoxFor(model => itemRole.isSelected, new { @class = "panel_checkbox" }) @Html.DisplayFor(model => itemRole.Role.Name)</div>
                                        @Html.HiddenFor(model=>itemRole.Role.RoleId)
                                    }
                                }
}

Any help is appreciated. Thanks.

Related posts

Recent Viewed