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

后端 未结 8 1147
日久生厌
日久生厌 2020-12-19 01:53

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/{articl

8条回答
  •  执念已碎
    2020-12-19 02:21

    Well, this is the combined solution I am using:

    Using same controller, with DefaultValue:

    public ActionResult Articles([DefaultValue(0)]int id)
    

    If DefaultValue was used, I refer to "MainArticles" view. If an article ID was provided - I refer to the "Articles" view with the appropriate article passed inside the ViewModel.

    In both cases the ViewModel is populated with the data both views need (complete article and category lists).

    Thanks everyone for your help!

提交回复
热议问题