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

Upvotes: 3

Views: 87

Answers (2)

Tony Abrams
Tony Abrams

Reputation: 4673

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();
}

Upvotes: 3

jefftrotman
jefftrotman

Reputation: 1114

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

Upvotes: 0

Related Questions