ASP.NET MVC控制器参数可选的(即指数(INT?ID)) [英] ASP.NET MVC controller parameter optional (i.e Index(int? id))
问题描述
我有以下情形:我的网站上显示的文章
I have the following scenario: my website displays articles (inputted by an admin. like a blog).
所以要查看的文章,该用户被称为首页/文章/ {文章ID}
So to view an article, the user is referred to Home/Articles/{article ID}.
然而,用户选择从Articles.aspx视图本身内,以查看哪些物品,使用jsTree列表
However, the user selects which article to view from within the Articles.aspx view itself, using a jsTree list.
所以,我什么,我需要做的是要能两种情况之间区分:用户正在访问的具体条款,或者他只是想进入主的文章页面。我试着设置了公司章程的控制器参数可选(INT?ID),但后来我有使用值时,控制器内的ID问题。
So I what I need to do is to be able to differentiate between two cases: the user is accessing a specific article, or he is simply trying to access the "main" articles page. I tried setting the "Articles" controller parameter as optional (int? id), but then I am having problems "using" the id value inside the controller.
什么是最佳的方式来处理这种情况?也许我只是需要一个更好的逻辑,用于检查ID参数是否是在URL提供?
What is the optimal manner to handle this scenario? Perhaps I simply need a better logic for checking whether or not an id parameter was supplied in the "url"?
我试图避免使用两个视图/控制器,只需出code-重复的原因。
I am trying to avoid using two views/controllers, simply out of code-duplication reasons.
推荐答案
使用单独的操作,如:
public ActionResult Articles() ...
public ActionResult Article(int id) ...
另外,它移动到一个文章控制器(使用默认路由的网址是:文章
和文章/详细信息/ {ID}
)
public class ArticlesController : Controller
{
public ActionResult Index() ...
public ActionResult Detail(int id) ...
}
如果你喜欢你贴仍然必须使用它,尝试下列操作之一:
If you still must use it like you posted, try one of these:
public ActionResult Articles(int id = 0)
{
if(id == 0) {
return View(GetArticlesSummaries());
}
return View("Article", GetArticle(id));
}
public ActionResult Articles(int? id)
{
if(id == null) {
return View(GetArticlesSummaries());
}
return View("Article", GetArticle(id.Value));
}
这篇关于ASP.NET MVC控制器参数可选的(即指数(INT?ID))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!