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.
C# int x; creates a value type integer which means that it cannot contain anything other than the usual range of integer values: 2147483647 to -2147483648 inclusive. Specifically, because it is a value type, it can't contain null .
It means that your parameter could have either integer value of null value. On your method you could use hasValue method to see if the parameter is null or has a valid integer value. Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM.
MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); The route names give the route a logical name. The named route can be used for URL generation. Using a named route simplifies URL creation when the ordering of routes could make URL generation complicated.
I don't know if you tried this, but instead if you are typing the value directly into the URL, then, instead of passing it like this:
controller/action/idValue
try passing it like this:
controller/action?id=value
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With