我正在使用Asp.Net Core 2.2 MVC和Entity Framework开发Web应用程序,
我正在尝试一个过程,在该过程中,用户将创建一个事件并提出一个问题,如果答案为是,则将加载页面,但如果答案为否,则会出现下一个问题。
我正在使用ViewModel将我的问题存储为列表。将第一个问题返回给我可以在每次单击按钮时遍历每个问题的最佳做法是什么?
我的视图模型如下:
public class PathwayViewModel
{
public List<StageQuestion> StageQuestion{ get; set; }
public Incident Incident { get; set; }
}
我的StageQuestion模型类如下
public class StageQuestion
{
// PK
public int Id { get; set; }
// FK to Incident Type
public int IncidentTypeId { get; set; }
// FK to Stage
public int StageId { get; set; }
public string QuestionText { get; set; }
public virtual IncidentType IncidentType { get; set; }
public virtual Stage Stage { get; set; }
}
我的控制器方法如下:
public IActionResult Pathway (int? id)
{
PathwayViewModel path = new PathwayViewModel();
var incident = _context.Incident
.Include(i => i.IncidentType)
.FirstOrDefault(m => m.Id == id);
path.Incident = incident;
var stageQuestions = _context.StageQuestion.Where(x => x.IncidentTypeId == incident.IncidentTypeId)
.Include(s => s.Stage)
.Include(o => o.Stage.Outcome)
.ToList();
path.StageQuestion = stageQuestions;
return View(path);
}
我的HTML如下:
@model Path2019.ViewModels.PathwayViewModel
@{
ViewData["Title"] = "Pathway";
}
<h1>Pathway</h1>
<table class="table">
<thead>
<tr>
<th>
Stage text
</th>
<th>
Question Text
</th>
<th>
Type of Incident
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.StageQuestion)
{
<tr>
<td>
@Html.DisplayFor(ModelItem => item.Stage.StageName)
</td>
<td>
@Html.DisplayFor(ModelItem => item.QuestionText)
</td>
<td>
@Html.DisplayFor(ModelItem => item.IncidentType.Type)
</td>
</tr>
}
</tbody>
</table>
答案 0 :(得分:0)
将第一个问题返回给我可以在每次单击按钮时遍历每个问题的最佳做法是什么?
仍然不清楚您的情况。根据您的描述,我假设您想在单击StageQuestion
按钮时一一显示Next
。如果要在服务器端过滤数据,则可以创建操作链接:
@Html.ActionLink("Next", "Pathway", new { index = ViewBag.NextIndex })
并修改您的视图模型以包含单个问题:
public class PathwayViewModel
{
public StageQuestion StageQuestion { get; set; }
}
然后在服务器端过滤记录:
public ActionResult Pathway(int? id,int? index)
{
int currentIndex = index.GetValueOrDefault();
if (currentIndex == 0)
{
ViewBag.NextIndex = 1;
}
else
{
ViewBag.NextIndex = index + 1;
}
........
PathwayViewModel path = new PathwayViewModel();
var stageQuestion = _context.StageQuestion.Where(x => x.IncidentTypeId == incident.IncidentTypeId)
.Include(s => s.Stage)
.Include(o => o.Stage.Outcome).OrderBy(x=>x.Id).Skip(currentIndex).Take(1).FirstOrDefault();
path.StageQuestion = stageQuestion;
return View(path);
}
使用上面的代码,您还应该添加以下两个逻辑:
@Html.ActionLink
如果以上代码示例不符合您的要求,请随时告诉我。