简体   繁体   中英

Problem with MVC Routing how to set default action of all Controller?

my RouteConfig like this :

 routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces: new[] { "GPTKish.Controllers" }
        );

When I enter for ex : http://localhost:23594/News , show me Index Action of News Controller but when i enter http://localhost:23594/NewsImages , get HTTP Error 403.14 - Forbidden!!!! and don't show index action of NewsImages Controller !!! where is wrong of my code? this is my newsImages controller

public class NewsImagesController : Controller
{
    private DatabaseContext db = new DatabaseContext();

    // GET: NewsImages
    public ActionResult Index(int selectedNewsid)
    {

        List<NewsImage> newsImages = db.NewsImages.Include(n => n.News).Where(c => c.NewsId == selectedNewsid).ToList();
        ViewBag.NewsTitle = newsImages[1].News.Title;
        return View(newsImages);
    }

thank you

It's because Index is expecting a parameter: selectedNewsid.

http://localhost:23594/NewsImages?selectedNewsid=0 or (if using the HttpGet Attribute) http://localhost:23594/NewsImages/0 should resolve.

Two options:

1) Make selectedNewsid be optional and (optional) add a HttpGet Attribute (due to the parameter)

[HttpGet("{selectedNewsid")]
public ActionResult Index(int selectedNewsid = 0)
{
    if(selectedNewsid == 0)
    {
       //Show all news images
    }else{
        List<NewsImage> newsImages = db.NewsImages.Include(n => n.News).Where(c => c.NewsId == selectedNewsid).ToList();
        ViewBag.NewsTitle = newsImages[1].News.Title;
        return View(newsImages);
    }
}

2) Create a new default action without a parameter

public ActionResult Index()
{
    return View();
}

This URL - http://localhost:23594/NewsImages - doesn't provide a value for selectedNewsId . If you want to show images for NewsId = 5, the URL should be http://localhost:23594/NewsImages?selectedNewsId=5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM