asp.net-mvc – 从另一个ActionResult返回ActionResult
发布时间:2020-12-16 07:27:27 所属栏目:asp.Net 来源:网络整理
导读:说我有以下代码,在记事本中嘲笑,所以原谅任何小错误:) //Default pagepublic ActionResult Index() { var musicViewModel { Albums = GetTopSellingAlbums(5),Genres = GetTopGenres(5),Artists = GetTopArtists(5) }; return View(musicViewModel); }[HttpP
说我有以下代码,在记事本中嘲笑,所以原谅任何小错误:)
//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),Artists = GetTopArtists(5) }; return View(musicViewModel); } 我关注的是,为了回发模型状态无效的任何错误,我需要再次生成视图模型,以便可以创建页面上使用这些对象的任何元素(流派,艺术家等).问题是它需要我将ActionResult中的一些代码复制并粘贴到ActionResult,似乎使我的代码不是很干. 有没有更好的方法来避免这样的重复代码?目前我只是将viewmodel需要的任何默认对象的生成移动到一个单独的方法和/或构造函数中,但是由于我必须生成整个控制器可能需要的所有对象,所以它有点乱.我希望我能做的就是将我的第二个Index Action指向第一个Index Action,并将其作为常规方法使用.虽然我尝试了几种不同的方法,但似乎无法将ActionResult返回到另一个ActionResult中. 有什么想法吗? 解决方法
您可以返回另一个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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 为什么我的ASP.Net站点在IIS7下运行需要很长时间才能在一段
- asp.net-mvc – 在ASP.NET MVC组织帐户中访问Azure AD Grap
- 在转发器asp.net中调用函数
- 【 .Net码农】认识ASP.NET MVC的5种AuthorizationFilter
- 无法使用dotnetopenauth通过twitter进行身份验证
- asp.net-mvc-3 – Razor语法不按我预期的方式工作
- asp.net – System.Linq.Dynamic不支持OrderByDescending(“
- asp.net – 在AJAX方法调用中的RegisterClientScriptBlock
- asp.net – 实体框架“等待操作超时”就简单的DeleteAll
- 当调用ASP.NET System.Web.HttpResponse.End()时,当前线程中
推荐文章
站长推荐
- asp.net-mvc – 将参数传递给html partial并在部
- asp.net – 保持visual studio从bin / on重建中删
- asp.net-mvc-3 – MVC3 Razor中的多语言实现
- 如何在asp.net中使用facebook api创建一个facebo
- asp.net – 无法加载文件或程序集“Microsoft.We
- Asp.Net MVC3到MVC4升级工具?
- asp.net-mvc – 具有多个参数的ActionLink
- asp.net-mvc – Asp.Net Mvc无法注销
- asp.net-mvc – HTTP错误500.19 – 内部服务器错
- asp.net-mvc-3 – 淘汰赛和全球化
热点阅读