【问题标题】:Returning an ActionResult from another ActionResult从另一个 ActionResult 返回一个 ActionResult
【发布时间】:2011-02-18 22:36:11
【问题描述】:

假设我有以下代码,在记事本中模拟,所以请原谅任何小错误:)

//Default page
public ActionResult Index()
    {
        var musicViewModel
        {
         Albums = GetTopSellingAlbums(5),
         Genres = GetTopGenres(5),
         Artists = GetTopArtists(5)
         };

        return View(musicViewModel);
    }

[HttpPost]
public ActionResult Index(MusicViewModel musicViewModel)
    {

        //For the example, pretend I have a class called musicStoreSubmission in my
        //viewmodel which holds a few different fields the user fills out.

        if(ModelState.IsValid)
        {
            //Do some actions based on the user submitting a form
        }

        //Else, refresh page with errors in Modelstate.
        var musicViewModel
        {
         Albums = GetTopSellingAlbums(5),
         Genres = GetTopGenres(5),
         Artists = GetTopArtists(5)
         };

        return View(musicViewModel);
    }

我担心的是,为了回发任何导致 ModelState 无效的错误,我需要再次生成视图模型,以便可以创建页面上使用这些对象的任何元素(流派、艺术家等)。问题是它需要我将一些代码从 ActionResult 复制并粘贴到 ActionResult,这似乎使我的代码不是很干燥。

有没有更好的方法来避免这样的重复代码?目前,我只是将视图模型所需的任何默认对象的生成移至单独的方法和/或构造函数中,但这有点混乱,因为我必须生成整个控制器可能需要的所有对象。我希望我能做的是将我的第二个索引操作指向第一个索引操作,并将其用作常规方法。虽然我尝试了几种不同的方法,但似乎无法将 ActionResult 返回到另一个 ActionResult。

有什么想法吗?

【问题讨论】:

    标签: asp.net-mvc controllers actionresult


    【解决方案1】:

    我建议应用Post/Redirect/Get 模式。它非常适合 MVC Web 应用程序。

    查看此答案以获取代码示例: ModelState.IsValid or Model.IsValid?

    【讨论】:

    • 该死,我只能将一个答案标记为有帮助?好吧,这对我也有很大帮助,所以感谢 Jakub。太糟糕了,所以不会让我两个都打勾:|
    【解决方案2】:

    您可以像这样返回另一个 ActionResult 方法:

    [HttpPost]
    public ActionResult Index(MusicViewModel musicViewModel)
    {
        if(ModelState.IsValid)
        {
            //Do some actions based on the user submitting a form
        }
        return MyAction();
    }
    

    或者您可以将发布的模型传递回 ViewResult

    [HttpPost]
    public ActionResult Index(MusicViewModel musicViewModel)
    {
        if(ModelState.IsValid)
        {
            //Do some actions based on the user submitting a form
        }
        return View(musicViewModel);
    }
    

    第二种方法更好,因为您不重建 ViewModel

    【讨论】:

    • 返回 MyAction();? Arg,我一直在尝试编写 return View("MyAction");现在想想,这很明显>_
    • 选项 #2,模型必须从 Get* 方法重新填充,所以他就回到了他开始的地方。
    • 如果我想返回与返回不同的视图怎么办(通过视图)
    猜你喜欢
    • 2012-12-08
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多