ASP.NET MVC 控制器参数可选(即 Index(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).
因此,要查看文章,用户将被称为 Home/Articles/{article ID}.
So to view an article, the user is referred to Home/Articles/{article ID}.
但是,用户使用 jsTree 列表从 Articles.aspx 视图本身中选择要查看的文章.
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.
处理这种情况的最佳方式是什么?也许我只是需要一个更好的逻辑来检查url"中是否提供了 id 参数?
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"?
我试图避免使用两个视图/控制器,仅仅是出于代码重复的原因.
I am trying to avoid using two views/controllers, simply out of code-duplication reasons.
推荐答案
使用单独的操作,例如:
Use separate actions, like:
public ActionResult Articles() ...
public ActionResult Article(int id) ...
或者将其移动到文章控制器(使用默认路由的 URL 将是:Articles
和 Articles/Detail/{id}
):
Alternatively move it to an Articles controller (urls using the default route will be: Articles
and Articles/Detail/{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 控制器参数可选(即 Index(int? id))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!