boo*_*ean 4 asp.net-mvc controllers actionresult
说我有以下代码,在记事本中嘲笑,所以原谅任何小错误:)
//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);
}
Run Code Online (Sandbox Code Playgroud)
我关注的是,为了回发ModelState无效的任何错误,我需要再次生成viewmodel,以便可以创建页面上使用这些对象的任何元素(流派,艺术家等).问题是它需要我将ActionResult中的一些代码复制并粘贴到ActionResult,似乎使我的代码不是很干.
有没有更好的方法来避免这样的重复代码?目前我只是将viewmodel需要的任何默认对象的生成移动到一个单独的方法和/或构造函数中,但是因为我必须生成整个控制器可能需要的所有对象,所以它有点乱.我希望我能做的就是将我的第二个Index Action指向第一个Index Action,并将其作为常规方法使用.虽然我尝试了几种不同的方法,但似乎无法将ActionResult返回到另一个ActionResult中.
有什么想法吗?
| 归档时间: |
|
| 查看次数: |
14974 次 |
| 最近记录: |