我如何在 MVC 中重载索引
How can i overload Index in MVC
我有索引页面,其中包含来自数据库的博客。首先,如果我不提供类别 ID,那么所有博客都必须进入索引页面。如果我给出类别,那么我想按类别 ID 显示博客,所以我需要使用索引重载。
public ActionResult Index(){List<Blog> blogs = db.Blogs.ToList();}
public ActionResult Index(int ID){List<Blog> blogs = db.Blogs.Where(x=>x.CategoryID==ID).ToList();}
但是当我想显示所有博客时,错误是这样的:
The current request for action 'Index' on controller type 'HomeController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult Index() on type SosyalSozluk.Areas.Blog.Controllers.HomeController
System.Web.Mvc.ActionResult Index(Int32) on type SosyalSozluk.Areas.Blog.Controllers.HomeController
删除第一个方法并更改第二个方法使参数可选
public ActionResult Index(int? ID)
{
IEnumerable<Blog> blogs = db.Blogs;
if (ID.HasValue)
{
blogs = blogs .Where(x=>x.CategoryID == ID.Value);
}
return View(model); // add `.ToList()` if you really need it
}
我有索引页面,其中包含来自数据库的博客。首先,如果我不提供类别 ID,那么所有博客都必须进入索引页面。如果我给出类别,那么我想按类别 ID 显示博客,所以我需要使用索引重载。
public ActionResult Index(){List<Blog> blogs = db.Blogs.ToList();}
public ActionResult Index(int ID){List<Blog> blogs = db.Blogs.Where(x=>x.CategoryID==ID).ToList();}
但是当我想显示所有博客时,错误是这样的:
The current request for action 'Index' on controller type 'HomeController' is ambiguous between the following action methods: System.Web.Mvc.ActionResult Index() on type SosyalSozluk.Areas.Blog.Controllers.HomeController System.Web.Mvc.ActionResult Index(Int32) on type SosyalSozluk.Areas.Blog.Controllers.HomeController
删除第一个方法并更改第二个方法使参数可选
public ActionResult Index(int? ID)
{
IEnumerable<Blog> blogs = db.Blogs;
if (ID.HasValue)
{
blogs = blogs .Where(x=>x.CategoryID == ID.Value);
}
return View(model); // add `.ToList()` if you really need it
}