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

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

    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

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

    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"}
    
    0 讨论(0)
提交回复
热议问题