【问题标题】:What is the difference between rendering a view and returning a view in ASP.NET MVC? Also, what is the difference between ActionResult and ViewResult?在 ASP.NET MVC 中呈现视图和返回视图有什么区别?另外,ActionResult 和 ViewResult 有什么区别?
【发布时间】:2023-01-18 19:20:52
【问题描述】:

我是 ASP.NET MVC 的新手。您能解释一下 ActionResult 和 ViewResult 之间的区别吗?如果使用 ActionResult 作为我的操作的返回类型而不是视图,这有关系吗? 渲染视图和返回视图是什么意思?

这是两个动作。如果我将 Index() 类型从 ViewResult 更改为 ActionResult 会有影响吗?

public ViewResult Index()
        {
            var customers = GetCustomers();

            return View(customers);
        }

public ActionResult Details(int id)
        {
            var customer = GetCustomers().SingleOrDefault(c => c.Id == id);

            if (customer == null)
                return HttpNotFound();
            return View(customer);
        } 

【问题讨论】:

    标签: c# asp.net asp.net-mvc api asp.net-mvc-4


    【解决方案1】:

    一种查看结果是一种行动结果. return View() 这一行中的 View 辅助方法实际上只是 return ViewResult() 的简写。所以,你要返回一个查看结果因为那是一种行动结果,您可以设置方法的返回类型(例如细节) 到行动结果.

    这是有关的更多信息查看结果https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.viewresult?view=aspnetcore-7.0

    对于问题的另一部分,渲染与返回视图。据我所知,在动作响应方法中返回一个视图(如您所示)。一个视图只是呈现当您使用局部视图并希望在另一个视图中呈现局部视图时。在这种情况下,部分视图在视图文件本身中呈现。所以你最终仍然只需要在动作响应方法中返回视图,因为局部视图将在其中呈现。

    有关渲染局部视图的更多信息,请查看此处:https://learn.microsoft.com/en-us/aspnet/core/mvc/views/partial?view=aspnetcore-7.0

    【讨论】:

      【解决方案2】:

      这是有关 ActionResult 和 ViewResult Difference Between ViewResult() and ActionResult() 的相同问题的链接

      TLDR:ActionResult 是一个抽象类,ViewResult 派生自它。在大多数情况下,您应该使用 ActionResult 作为方法返回类型,因为它更方便和灵活(您可以返回从 AcionResult 派生的任何类)。但是,如果您将使用 ViewResult 作为方法的返回类型,则必须返回 ViewResult 或派生自它的任何不同类

      【讨论】:

        猜你喜欢
        • 2012-01-24
        • 1970-01-01
        • 2011-01-17
        • 1970-01-01
        • 2022-08-05
        • 1970-01-01
        • 1970-01-01
        • 2010-11-01
        • 1970-01-01
        相关资源
        最近更新 更多