如何将PartialView中的项目列表发布到控制器?

时间:2016-05-05 05:20:05

标签: c# asp.net-mvc

实际上这是非常简单的情况,但我无法理解如何使这项工作。因此,有 PartialView 中呈现的复选框列表。数据从父 ViewModel 传递到PartialView中的子 ViewModel 。所有这些都是由表单包裹的,遗憾的是我无法从 PartialView 获取数据 父ViewModel:

public class UserProgramsViewModel
    {
        public int Id { get; set; }
        [Required(ErrorMessage = "Введите название")]
        [DisplayName("Название")]
        public string ProgramName { get; set; }
        [DisplayName("Пользователь")]
        public string UserName { get; set; }
        [DisplayName("Пользователь")]
        public int UserId { get; set; }
        [DisplayName("Дни Программы")]
        public ICollection<ProgramDaysDTO> ProgramDays { get; set; }
        public IEnumerable<DaysViewModel> Days { get;  set;} //Passed to Partial
    }

Child ViewModel:

public class DaysViewModel
    {
        public int Id { get; set; }
        public string DayName { get; set; }
    }

家长视图:

@Html.Partial("Days", Model.Days)

PartialView(这里我们使用属性名称'Days'将其绑定到Parent模型)

@model IEnumerable<BBN.Admin.ViewModels.DaysViewModel>
<ul class="list-group col-lg-2">
    @foreach (var item in Model)
    {
        <li class="list-group-item"><input type="checkbox" name="Days" value="@item.Id" /> @item.DayName</li>
    }
</ul>

控制器:

        [HttpPost]
        [RBAC]
        public async Task<ActionResult> Create(UserProgramsViewModel model)
        {
            var groups = await _us.GetAll();
            ViewBag.Users = groups.Select(x => new SelectListItem
            {
                Text = x.Login,
                Value = x.Id.ToString()
            });
            var dto = new UserProgramsDTO
            {
                ProgramName = model.ProgramName,
                UserId = model.UserId,
                Days = model.Days
            };
            var result = await _ps.Create(dto);
            if (result.IsSuccess == (BLL.Utilities.Enums.IsSuccess)Enums.IsSuccess.Success) return RedirectToAction("Index");
            else return View("Create");
        }

2 个答案:

答案 0 :(得分:1)

您可以使用FormCollection。将item.DayName分配给输入的名称属性:

<强> PartialView(片段):

<li class="list-group-item">
      <input type="checkbox" name="@(item.DayName)Days" @if (item.Id > 0) { <text>checked</text> } /> @item.DayName
</li>

然后处理FormCollection参数并填写模型的Days属性及其帮助:

<强>控制器:

[HttpPost]
[RBAC]
public async Task<ActionResult> Create(UserProgramsViewModel model, FormCollection formCollection)
{
    model.Days = new List<DaysViewModel>();
    foreach(var key in formCollection.AllKeys.Where(x => x.Contains("Days")))
        model.Days.Add(new DaysViewModel { Id = formCollection[key] == "on" ? 1 : 0, DayName = key.Replace("Days", "")} );

     //other stuff...
}

答案 1 :(得分:0)

您是否在控制器的父视图中设置了“Days”的值? 比如假设您的父视图名称是“Parent”,那么您应该这样写,

public ActionResult Parent()
{
     UserProgramsViewModel loUser = new UserProgramsViewModel(); 
       //Assign Your values here

     View(loUser); 
}

所以你可能不会在这里获得Null值。