C# MVC5-具有复杂类型的ViewModel
我找不到解决这种问题的办法。如果这是一个重复的职位,我很抱歉 我正在对我的解决方案进行建模 My ViewModel(ZooAnimalsViewModel)包含可能的动物列表和ICollection 我正在尝试填充Zoo和Animal之间的链接表-该表是ZooAnimalDetail。我将ZooAnimalsViewModel作为模型传递给主视图 并将动物作为EditorTemplate文件allAnimals.cshtml的模型 从我所看到的情况来看,我应该使用框架来生成列表,方法是在EditorTemplate目录中创建一个与我要显示的列表/集合同名的文件 我想显示所有动物的列表,并使用它来更新ICollection ZoonanimalDetail中包含的内容-我不知道如何编写Html帮助程序来绑定它们 简化的ViewModel ZooAnimalViewModel具有以下属性:C# MVC5-具有复杂类型的ViewModel,c#,asp.net-mvc-5,viewmodel,html-helper,checkboxfor,C#,Asp.net Mvc 5,Viewmodel,Html Helper,Checkboxfor,我找不到解决这种问题的办法。如果这是一个重复的职位,我很抱歉 我正在对我的解决方案进行建模 My ViewModel(ZooAnimalsViewModel)包含可能的动物列表和ICollection 我正在尝试填充Zoo和Animal之间的链接表-该表是ZooAnimalDetail。我将ZooAnimalsViewModel作为模型传递给主视图 并将动物作为EditorTemplate文件allAnimals.cshtml的模型 从我所看到的情况来看,我应该使用框架来生成列表,方法是在Ed
public class ZooAnimalViewModel
{
public Zoo zoo { get; set; }
public ICollection<ZooAnimalDetail> ZooAnimalDetail { get; set; }
public List<Animal> allAnimals { get; set; }
}
动物的简化模型如下:
public partial class ZooAnimalDetail
{
public int zooID { get; set; }
public int animalID { get; set; }
public bool animalDefault { get; set; }
public virtual Animal Animal { get; set; }
public virtual Zoo Zoo { get; set; }
}
public partial class Animal
{
public Animal()
{
ZooAnimalDetails = new HashSet<ZooAnimalDetail>();
}
public int animalID { get; set; }
public string animalName { get; set; }
public virtual ICollection<ZooAnimalDetail> ZooAnimalDetails { get; set; }
}
我不再需要我的动物模型中的所有动物列表
看起来不错 快速说明-我在添加布尔值IsChecked字段时使用了NotMapped属性,如下面的
[NotMapped]public bool IsChecked{get;set;}
@model ZooAnimalViewModel
@using (Html.BeginForm())
{
@Html.HiddenFor(x => Model.zoo.zooID)
<table>
<tr>
<th>Animal Name</th>
<th>Add</th>
<th>Set as default</th>
</tr>
@Html.EditorFor(x => x.allAnimals)
</table>
<input type="submit" value="Save" />
}
@model DatabaseName.Models.Animal
@Html.HiddenFor(x => x.animalID)
<tr>
<td>@Html.CheckBoxFor(x => x.ZooAnimalDetail.??)</td> @*PROBLEM 1*@
<td>@Html.CheckBoxFor(x => x.ZooAnimalDetail.Add(animalDefault))</td> @*PROBLEM 2*@
<td>@Html.DisplayFor(x => x.animalName)</td>
</tr>
@model DatabaseName.Models.ZooAnimalDetail
@Html.HiddenFor(x => x.animalID)
<tr>
<td>@Html.CheckBoxFor(x => x.IsChecked)</td>
<td>@Html.CheckBoxFor(x => x.animalDefault)</td>
<td>@Html.DisplayFor(x => x.Animal.animalName)</td>
</tr>
if (ModelState.IsValid)
{
db.Zoos.Add(zavm.zoo);
db.SaveChanges();
//grab the new zooID
int lastzooID = db.Zoos.Max(item => item.zooID);
foreach (ZooAnimalDetail z in zavm.ZooAnimalDetail)
{
if (z.IsChecked == true)
{
z.zooID = lastzooID;
db.ZooAnimalDetails.Add(z);
}
}
db.SaveChanges();
return RedirectToAction("Index");
}