【问题标题】:Asp.net core how to display IEnumerable model one by oneasp.net core如何一一显示IEnumerable模型
【发布时间】:2021-12-06 07:02:34
【问题描述】:

我有一个 IEnumerable 模型,想要在视图中逐项显示。

   public IActionResult Index()
   {
       var model = _context.Question.ToList();
       return View(model);
   }

我的观点类似于下面的观点。我希望通过按下一个和上一个按钮来显示下一个和上一个项目

这是我的观点

   <div>
    <p>
        @foreach (var item in Model.Take(1))
        {
            @Html.Raw(item.QuestionContent)
            foreach (var item2 in item.Answers)
            {
                @Html.Raw(item2.AnswerContent)
                <input type="checkbox" />
            }
        }
    </p>

    <div>
        <a id="btnnext" class="btn">
            Next
        </a>
        <a id="btnprev" class="btn">
            Prev
        </a>
    </div>

【问题讨论】:

    标签: javascript jquery asp.net asp.net-core


    【解决方案1】:

    这是一个完整的工作演示,您可以关注:

    型号:

    public class Question
    {
        public int Id { get; set; }
        public string QuestionContent { get; set; }
        public List<Answer> Answers { get; set; }
    }
    public class Answer
    {
        public int Id { get; set; }
        public string AnswerContent { get; set; }
    }
    

    查看:

    @model IEnumerable<Question>
    @{ 
        int current = (int)ViewBag.CurrentIndex;
    
    }
    <div>
        <p>
    
            @Html.Raw(Model.ElementAt(current).QuestionContent)
            @foreach (var item in Model.ElementAt(current).Answers)
            {
                @Html.Raw(item.AnswerContent)
                <input type="checkbox" />
            }
    
        </p>
        @{
            var prevDisabled = !(bool)ViewBag.HasPreviousPage ? "disabled" : "";
            var nextDisabled = !(bool)ViewBag.HasNextPage ? "disabled" : "";
        }
    
        <a asp-action="Index"
           asp-route-index="@ViewBag.PreviousIndex"
           class="btn btn-default @prevDisabled">
            Previous
        </a>
        <a asp-action="Index"
           asp-route-index="@ViewBag.NextIndex"
           class="btn btn-default @nextDisabled">
            Next
        </a>
    </div>
    

    控制器:

    public IActionResult Index(int index)
    {
        var model = _context.Question.ToList();
        ViewBag.CurrentIndex = index;
        ViewBag.PreviousIndex = index - 1;
        ViewBag.NextIndex = index + 1;
        ViewBag.HasPreviousPage = ViewBag.PreviousIndex == -1 ? false : true;
        ViewBag.HasNextPage = ViewBag.NextIndex == model.Count() ? false : true;         
        return View(model);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多