实际上这是非常简单的情况,但我无法理解如何使这项工作。因此,有 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");
}
答案 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值。