我有一个View,它显示来自ViewModel的集合,用户可以在其中更新每个集合项的属性(熟练程度的“级别”)。
这是视图:
@model Consultants.ViewModels.ProgramsViewModel
@{
ViewBag.Title = "Programkunskaper";
}
<h2>@ViewBag.Title</h2>
<div id="formDiv">
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Ny arbetserfarenhet</legend>
<table>
<tr>
<th>
Program
</th>
<th>
Nivå
</th>
</tr>
@Html.EditorFor(m => m.ProgramSkills, "ProgramSkills")
@*Using editorformodel instead of for loop according to tip here: http://stackoverflow.com/questions/5420471/use-dropdownlistfor-with-foreach-in-asp-net-mvc-view*@
</table>
<p>
<input type="submit" value="Spara" />
</p>
</fieldset>
}
</div>
编辑器模板:
@model Consultants.Models.ProgramSkill
<tr>
<td>@Model.Program.Name
</td>
<td>
@Html.DropDownListFor(
model => model.Level,
new SelectList(new[] { 0, 1, 2, 3, 4, 5 },
Model.Level
)
)
</td>
</tr>
这是我的行动方法(我知道,使用索引视图看起来有点奇怪,我可能会改变它,但现在不要介意):
public ActionResult Index()
{
Consultant consultant = _repository.GetConsultantByUserName(User.Identity.Name);
ViewBag.Consultant = consultant;
if (consultant.ProgramSkills.Count == 0)
{
List<Program> programs = _repository.GetAllPrograms();
foreach (var program in programs)
{
consultant.ProgramSkills.Add(new ProgramSkill { Program = program });
}
_repository.Save();
}
ProgramsViewModel vm = new ProgramsViewModel();
vm.ProgramSkills = consultant.ProgramSkills.ToList();
return View(vm);
}
[HttpPost]
public ActionResult Index(ProgramsViewModel vm, FormCollection collection)
{
Consultant consultant = _repository.GetConsultantByUserName(User.Identity.Name);
List<ProgramSkill> programSkills = consultant.ProgramSkills.ToList();
for (int i = 0; i < programSkills.Count; i++)
{
var programSkill = programSkills[i];
programSkill.Level = vm.ProgramSkills[i].Level;
}
_repository.Save();
vm.ProgramSkills = programSkills;
return View(vm);
}
现在,即使这很好用,我意识到我需要能够通过它的Program.Category属性对ProgramSkill项进行分组。但接下来我会遇到一些问题:
如何对它们进行分组并将它们在ViewModel中传递给View?
对象是Program,ProgramSkill和Consultant,其中Program和Consultant之间存在多对多关系,而ProgramSkill是联结表(因为它具有附加属性“Level”而需要)。
如果我有一个Linq表达式根据它对它们进行分组,并且可以使它成为View可以使用的ViewModel,那么在回发到Controller之后我将如何再次更新模型?
如果可以完成代码,代码将会变得更加复杂,只是为了按Program.Category对ProgramSkill项进行分类。但与此同时,如果项目未被分类,View将具有非常差的可用性......
任何人都知道一个很好的解决方案吗?
答案 0 :(得分:0)
我认为您要做的是添加另一个视图模型
ProgramSkillsModel
{
string Category {get;set;}
IList<ProgramSkill> Skills {get;set;}
}
然后在你的控制器索引()
ProgramsViewModel vm = new ProgramsViewModel();
vm.ProgramSkills = consultant.ProgramSkills.GroupBy(c => c.Category)
.Select(c => new ProgramSkillsModel{
Category = c.Key,
Skills = c.ToList(),
});
希望这有效。这只是伪代码