在一个人的Details
视图中,我还要显示DbContext
中的其他对象,表Survey
的每个记录都是准确的。所以我将它们插入ViewBag
人的控制者行动:
[HttpPost]
public ActionResult _Survey1(int id) {
System.Diagnostics.Debug.WriteLine("PASSED ID: " + id);
Person person = db.Persons.Find(id);
ViewBag.Surveys = db.Surveys.ToList();//HERE I insert Surveys to ViewBag
return PartialView(person);
}
并尝试在View中迭代它们:
@model WebApplication2.Models.Person
<hr />
<h2>Survey</h2>
<input type="button" id="Coll" value="Collapse" onclick="javascript:CollapseDiv()" />
<p>
@Html.DisplayFor(x => ViewBag.Surveys.Count)
</p>
@foreach (var survey in ViewBag.Surveys) {
<p>
@using (Html.BeginForm()) {
<text>ANK</text>
@Html.DisplayFor(x => survey.Questions.Count)
@Html.EditorFor(x => survey.Questions)
<input type="submit" />
}
</p>
}
<hr />
问题是我得到了:
问题:由于tschmit007建议如何定义可以采用Person
和`IEnumerable并将数据传递给它的模型?
答案 0 :(得分:3)
定义包含Person
和Surveys
属性的视图模型。例如
public class MyViewModel
{
public Person Person { get; set; } // or create properties for each property or Person
public IEnumerable<Survey> Surveys { get; set; }
}
显示页面时
[HttpGet]
public ActionResult Details (int ID)
{
MyViewModel model = new MyViewModel();
model.Person = db.Persons.Find(id);
model.Surveys = db.Surveys;
return View(model);
}
并在视图中
@model YourAssembly.MyViewModel
@Html.DisplayFor(m => m.Person.SomeProperty) // display properties of person
@foreach (var survey in Model.Surveys) {
@using (Html.BeginForm()) {
@Html.EditorFor(x => survey.Questions)
<input type="submit" />
}
}
答案 1 :(得分:1)
我在没有创建ViewModel的情况下将数据作为元组传递。元组出现在.NET 4.0中。这完成了这项工作:
public ActionResult _Survey1(int id) {
System.Diagnostics.Debug.WriteLine("PASSED ID: " + id);
Person person = db.Persons.Find(id);
var tuple = new Tuple<Person, List<Survey>>(person, db.Surveys.ToList()){};
return PartialView(tuple);
}
@using WebApplication2.Models
@model System.Tuple<Person, List<Survey>>
<hr />
<h2>Surveys</h2>
<input type="button" id="Coll" value="Collapse" onclick="javascript:CollapseDiv()" />
<p>
@Html.DisplayFor(x => Model.Item2.Count)
</p>
@foreach (var survey in Model.Item2) {
using (Html.BeginForm()) {
<text>Number of Questions in a Survey</text>
@Html.DisplayFor(x => survey.Questions.Count)
<p/>
@Html.EditorFor(x => survey.Questions)
<input type="submit" />
}
}
<hr />
答案 2 :(得分:0)
@Html.DisplayFor(x => ViewBag.Surveys.Count)
希望您使用模型的一部分ViewBag
应为x
。您需要做的是删除For
,这使得它不使用模型。
改为使用:
@Html.Display(ViewBag.Surveys.Count)
@Html.Display(survey.Questions.Count)
@Html.Editor(survey.Questions)
Display
最有可能被排除在外:
<p>@ViewBag.Surveys.Count</p>
也会奏效。