ASP.NET MVC controller parameter optional (i.e Index(int? id)) ASP.NET MVC controller parameter optional (i.e Index(int? id)) asp.net asp.net

ASP.NET MVC controller parameter optional (i.e Index(int? id))


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));}


First of all, I agree with @Steve :). But if you really want to use

int? id

you can just check in your controller method if the id is set using a simple

if(id == null)

and if so, load all articles from your DB (or something alike) and pass these to your view (either directly, or by using a view model). If the id is set you just load the article having that id from your DB and send that to the view (possibly in a list as well if you dont use view models)?

Than in your view just load all articles in the list with articles supplied to the view. Which contains either all or just one.

Complete dummy code

public ActionResult showArticles(int? id){   List<Articles> aList;   if(id == null){       aList = repository.GetAllArticles().ToList();   }else{      aList = new List<Articles>();       aList.add(repository.GetArticleByID(id));   }   return View(aList);}

Your View has something like:

<% Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<List<Articles>>"%>foreach(Articles a in Model)    //display article

And you call it using either of the next two options:

html.ActionLink("one article","showArticles","Articles",new {id = aID},null}html.ActionLink("all articles","showArticles","Articles"}


Define a default value for the Id that you know indicated no value was supplied - usually 0.

public ActionResult Articles([DefaultValue(0)]int Id){  if (Id == 0)    // show all  else    // show selected..