Tom Teman Tom Teman - 18 days ago 11
ASP.NET (C#) Question

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).

So to view an article, the user is referred to Home/Articles/{article ID}.

However, the user selects which article to view from within the Articles.aspx view itself, using a jsTree list.

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.

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.

Answer

Use separate actions, like:

public ActionResult Articles() ...
public ActionResult Article(int 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));
}