代码之家  ›  专栏  ›  技术社区  ›  JasCav

我需要每个动作的视图吗?

  •  4
  • JasCav  · 技术社区  · 15 年前

    我的问题是-在这里应该做什么。在方法结束时,我返回响应。重定向('\Controller\View'),因此我返回另一个视图。有没有可能在一个动作结束时不必返回任何类型的视图?这里的最佳实践是什么?

    4 回复  |  直到 15 年前
        1
  •  2
  •   John Farrell    15 年前

    如果因为用户单击了链接而需要重定向用户,请重定向用户。

    如果您使用Ajax或其他技术发布,并且没有有意义的响应,请更改controller action方法,使其返回类型为void。

        2
  •  1
  •   Jeff Camera    15 年前

    如果您使用AJAX发布,并且不需要重定向用户或显示新视图,那么您可能需要考虑返回一个字符串,向用户显示确认消息。

        3
  •  0
  •   davehauser    15 年前

    我想说的是,一个操作应该总是处理一个HTTP请求。如果它返回一个视图或重定向到另一个操作,两者都是可能的。

    [HttpGet] // Handles only GET requests
    public ActionResult Edit(int id)
    {
         // get entity from repository
         // and create edit model
         return View(editModel);
    }
    
    [HttpPost]
    public ActionResult Edit(EntityEditModel editModel)
    {
         // if ModelState is valid, save entity
         // and if success redirect to index 
         return RedirectToAction("Index");
    }
    

        4
  •  0
  •   pgmer    11 年前

    可以使用tilde语法提供视图的完整路径,如下所示:

    public ActionResult Index() 
    {
    ViewBag.Message = "Modify this template to jump-start
    your ASP.NET MVC application.";
    return View("~/Views/Example/Index.cshtml");
    }
    

    视图引擎用于查找视图的内部查找机制。