【问题标题】:Why Can I not do a subrequest for a Partial View for each request?为什么我不能为每个请求执行部分视图的子请求?
【发布时间】:2017-01-10 21:48:13
【问题描述】:

_Layout.cshtml,我有这部分代码

<div>
      @Html.Action("BestStudent", "Student")
</div>

在学生控制器中,我创建了 BestStudent 方法,如下所示

public class StudentController : Controller
{
    private UniversityInitial dbAllStudents  = new UniversityInitial();

    [ChildActionOnly]
    public ActionResult BestStudent()
    {
        var best = dbAllStudents.Students
            .Where(s => s.LastName.StartsWith("M")&s.FirstName.StartsWith("E") & s.City.StartsWith("T"));
        return PartialView("_BestStudent", best);
    }
}

在 Views/Shared 文件夹中,我为学生模型创建了名为 _BestStudent.cshtml 强类型的局部视图,如下所示:

@model UniversityApp.Models.Student

<h3 class="text-danger">Student of the year</h3>
Name : @Model.FirstName
Last Name : @Model.LastName
City: @Model.City

构建成功,但是当我运行它时,我遇到了一个异常,例如:

“执行处理程序'System.Web.Mvc.HttpHandlerUtil的子请求时出错...

断点在下面的代码行:

<div>
    @Html.Action("BestStudent", "Student")
</div>

所以我猜这里出了点问题,但我不知道是什么

【问题讨论】:

  • 你到底在做什么?告诉我你的情况
  • 因为您的查询返回Student 的集合,而不是您的视图所需的单个Student(因此引发异常)。更改查询以添加.FirstOrDefault()
  • 也把完整的错误不仅仅是它的一部分
  • @StephenMuecke 您的建议效果很好,正是我所需要的。

标签: c# asp.net-mvc html-helper asp.net-mvc-partialview


【解决方案1】:

更新

像下面这样修复这个查询:

var best = dbAllStudents.Students
                        .Where(s => s.LastName.StartsWith("M")&s.FirstName.StartsWith("E") & s.City.StartsWith("T")).FirstOrDefault();
return PartialView("_BestStudent", best);

感谢@StephenMuecke

【讨论】:

    猜你喜欢
    • 2014-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多