如何减少ASP.NET MVC中ActionResult中的参数数量?

时间:2011-02-15 12:55:16

标签: c# asp.net asp.net-mvc

public ActionResult Archive(string id, int ids = 0, int idd = 0)
{
    switch (id)
    {
        case "News":
            ViewData["ArtCat"] = "News";
            ids = 1;
            break;
        case "Opinions":
            ViewData["ArtCat"] = "Opinions";
            ids = 2;
            break;
        case "Features":
            ViewData["ArtCat"] = "Features";
            ids = 3;
            idd = 4;
            break;
    }
    var article = from c in _entity.Articles
                    where (c.ArtCatID == ids) || (c.ArtCatID == idd)
                    orderby c.ID
                    select c;
    return View(article);
}

还有其他方法可以提高效率吗?

2 个答案:

答案 0 :(得分:1)

首先,设置一条可以处理您正在寻找的路线:

Route.MapRoute(
    "ArticleArchive"
    "/Article/Archive/{category}/{archiveId}",
    new { controller = Article, action = Archive, category="all", archiveId = UrlParameter.Optional }
);

然后,在您的操作结果中,您可以执行以下操作:

private _entity = new ArticleRepository();
public ActionResult Archive(string category, int archiveId)
{
    var article = entity.GetArticleArchivesByCategoryAndID(category, archiveId);
    return View(article);
}

您的存储库类应该实际处理获取文章:

public class ArticleRepository
{
    private MyEntityContext _entity = new MyEntityContext();
    public IEnumerable<Article> GetArticleArchivesByCategoryAndID(string category, string id)
    {
        var articles = from c in _entity.Articles
            where (c.Category == category && c.ArtCatID == id)
            orderby c.ID
            select c;
    return articles;
    }

}

不需要ViewData,并且您不需要在操作结果中包含switch语句。此代码有点不稳定,因为您iddids的需求并不是很明确。如果你能澄清一下,那会有所帮助。

答案 1 :(得分:0)

  • 创建一个ActicleType枚举
  • 使用此枚举代替id
  • 的字符串
  • 摆脱ids和idd
  • 将ArticlyType字段添加到Acticles表
  • 按文章类型查询