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

后端 未结 8 1142
日久生厌
日久生厌 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:01

    this to me sounds like two separate pages and should be treated as such. You have the "Main" view page and the "articles" page.

    I would split it into two actions. They should not be much dupliation at all really, both should be doing a call to get the same ModelView and the article will simply get the a extension to that!

    0 讨论(0)
  • 2020-12-19 02:05

    Make the parameter required then set a default value in the routing that is a value that isn't a valid index and indicates to your action that it should render the main page.

    0 讨论(0)
  • 2020-12-19 02:06

    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));
    }
    
    0 讨论(0)
  • 2020-12-19 02:12

    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
    ..
    
    0 讨论(0)
  • 2020-12-19 02:15

    The easiest solution is to have two different actions and views but name the actions the same.

    public ViewResult Articles()
    {
       //get main page view model
       return View("MainPage", model);
    }
    
    public ViewResult Articles(int id)
    {
       // get article view model
       return View(model);
    }
    
    0 讨论(0)
  • 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!

    0 讨论(0)
提交回复
热议问题