首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从另一个ActionResult返回ActionResult

从另一个ActionResult返回ActionResult
EN

Stack Overflow用户
提问于 2011-02-19 06:36:11
回答 2查看 15.3K关注 0票数 4

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

代码语言:javascript
复制
//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,这似乎使我的代码不是很枯燥。

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

有什么想法吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-02-19 06:48:07

您可以返回另一个ActionResult方法,如下所示:

代码语言:javascript
复制
[HttpPost]
public ActionResult Index(MusicViewModel musicViewModel)
{
    if(ModelState.IsValid)
    {
        //Do some actions based on the user submitting a form
    }
    return MyAction();
}

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

代码语言:javascript
复制
[HttpPost]
public ActionResult Index(MusicViewModel musicViewModel)
{
    if(ModelState.IsValid)
    {
        //Do some actions based on the user submitting a form
    }
    return View(musicViewModel);
}

第二种方法更好,因为您不需要重新构建ViewModel

票数 4
EN

Stack Overflow用户

发布于 2011-02-19 07:01:50

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

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

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5047303

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档