Mapmvcattributeroutes with Pagedlist.MVC

Asked

Viewed 449 times

3

I’m using the routes.MapMvcAttributeRoutes(); to decorate my actions with the Url I want to appear in the browser, and it has worked very well, however, when using with the PagedList I’ve been having a problem that I can’t solve.

below follows the code of my controller:

    [Route("sala-de-impresa/noticias/{page?}")]
    public ActionResult Noticia(int? page)
    {
        var model = _ctx.Noticias.Include("Categoria").Where(n => n.Status && n.DataPublicacao <= DateTime.Now).OrderByDescending(n => n.NoticiaId);

        const int pageSize = 20;
        var pageNumber = (page ?? 1);
        return View(model.ToPagedList(pageNumber, pageSize));
    }

Here is the View code that makes the pagination:

@Html.PagedListPager(Model, page => Url.Action("Noticia", new { page, currentFilter = ViewBag.CurrentFilter }), PagedListRenderOptions.OnlyShowFivePagesAtATime)

To the Home page the Url and accessed smoothly,

Ex: localhost:xxxx/newsroom/newsroom

But when trying to advance the pagination to page 2 for example:

localhost:xxxx/newsroom/2

get the bug:

Erro de Servidor no Aplicativo '/'.

Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL.

The request has found the following matching controller types: 
WP_AMERON.Controllers.NoticiaController
WP_AMERON.Controllers.SalaImprensaController

Descrição: Ocorreu uma exceção sem tratamento durante a execução da atual solicitação da Web. Examine o rastreamento de pilha para obter mais informações sobre o erro e onde foi originado no código. 

Detalhes da Exceção: System.InvalidOperationException: Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL.

The request has found the following matching controller types: 
WP_AMERON.Controllers.NoticiaController
WP_AMERON.Controllers.SalaImprensaController

Erro de Origem: 

Exceção sem tratamento foi gerada durante a execução da atual solicitação da Web. As informações relacionadas à origem e ao local da exceção podem ser identificadas usando-se o rastreamento de pilha de exceção abaixo.

Rastreamento de Pilha: 


[InvalidOperationException: Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL.

The request has found the following matching controller types: 
WP_AMERON.Controllers.NoticiaController
WP_AMERON.Controllers.SalaImprensaController]
   System.Web.Mvc.DefaultControllerFactory.GetControllerTypeFromDirectRoute(RouteData routeData) +373
   System.Web.Mvc.DefaultControllerFactory.GetControllerType(RequestContext requestContext, String controllerName) +141
   System.Web.Mvc.DefaultControllerFactory.System.Web.Mvc.IControllerFactory.GetControllerSessionBehavior(RequestContext requestContext, String controllerName) +53
   System.Web.Mvc.MvcRouteHandler.GetSessionStateBehavior(RequestContext requestContext) +131
   System.Web.Mvc.MvcRouteHandler.GetHttpHandler(RequestContext requestContext) +33
   System.Web.Mvc.MvcRouteHandler.System.Web.Routing.IRouteHandler.GetHttpHandler(RequestContext requestContext) +10
   System.Web.Routing.UrlRoutingModule.PostResolveRequestCache(HttpContextBase context) +9767524
   System.Web.Routing.UrlRoutingModule.OnApplicationPostResolveRequestCache(Object sender, EventArgs e) +82
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69

Informações sobre a Versão: Microsoft .NET Framework Versão:4.0.30319; Versão do ASP.NET:4.0.30319.33440

But if I edit the Url and put it like this:

localhost:xxxx/newsroom/newsroom? page=2

Paging works normally.

EDIT:

Controller Noticia and Salaimpresa code

public class SalaImprensaController : Controller
    {
        readonly AmeronContext _ctx = new AmeronContext();

        [Route("sala-de-impresa/noticias/{page?}")]
        public ActionResult Noticia(int? page)
        {
            var model = _ctx.Noticias.Include("Categoria").Where(n => n.Status && n.DataPublicacao <= DateTime.Now).OrderByDescending(n => n.NoticiaId);

            const int pageSize = 20;
            var pageNumber = (page ?? 1);
            return View(model.ToPagedList(pageNumber, pageSize));
        }

        [Route("sala-de-impresa/videos")]
        public ActionResult Videos(int? page)
        {
            var model = _ctx.Videos.ToList().OrderByDescending(n => n.VideoId).ToList();

            const int pageSize = 9;
            var pageNumber = (page ?? 1);
            return View(model.ToPagedList(pageNumber, pageSize));
        }

        [Route("sala-de-impresa/galerias/{page?}")]
        public ActionResult Galerias(int? page)
        {
            var model = _ctx.Galerias.ToList().OrderByDescending(n => n.GaleriaId).ToList();

            const int pageSize = 9;
            var pageNumber = (page ?? 1);
            return View(model.ToPagedList(pageNumber, pageSize));
        }
    }




public class NoticiaController : Controller
    {
        readonly AmeronContext _ctx = new AmeronContext();

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

        public ActionResult CarouselNoticias()
        {
            var model = _ctx.Noticias.Include("Categoria").Where(n => n.Status && n.DataPublicacao <= DateTime.Now && n.Destaque).OrderByDescending(n => n.NoticiaId);
            return PartialView("_Carroussel", model);
        }

        public ActionResult Noticias()
        {
            var model = _ctx.Noticias.Include("Categoria").Where(n => n.Status && n.DataPublicacao <= DateTime.Now && n.Destaque == false).OrderByDescending(n => n.NoticiaId);
            return PartialView("_Noticias", model);
        }

        [Route("{categoria}/{id}/{titulo}")]
        public ActionResult Details(int id)
        {
            var noticia = _ctx.Noticias.Include("Categoria").FirstOrDefault(n => n.NoticiaId == id);

            if (noticia == null)
            {
                return RedirectToAction("NotFound");
            }

            if (noticia.ViewNumber == null)
            {
                noticia.ViewNumber = 1;
            }
            else
            {
                noticia.ViewNumber++;
            }

            _ctx.Entry(noticia).State = EntityState.Modified;
            _ctx.SaveChanges();

            var categoria = noticia.Categoria.Nome;
            var widget = _ctx.Noticias.Include("Categoria").ToList().Where(n => n.Categoria.Nome == categoria && n.Status).OrderByDescending(n => n.NoticiaId).Take(15);

            ViewBag.Noticia = noticia;

            return View(widget);
        }
  • @Fccdias after commenting on this routing worked, but did not understand why this routing is interfering with another.

  • 1

    And for you to leave with the mistake and this serve as a basis for others who have the same mistake back what was

2 answers

2


Modification:

@Html.PagedListPager(Model, page => Url.Action("Noticia", "Noticia", new { page = page, currentFilter = ViewBag.CurrentFilter }), PagedListRenderOptions.OnlyShowFivePagesAtATime)

In the Url.Action if you can put the Controller and the Action that he picks up from routing automatically, I based that controller is News story and its action is News story, if it is not change in Url.Action being the first to Action and the second Controller, then comes the new that are pagination and filter ...

Error:

Duplication of Routing

The request has found the following types of matching controllers:

  • WP_AMERON.Controllers.NoticiaController
  • WP_AMERON.Controllers.SalaImprensaController

There is a routing in Noticiacontroller [Route("{categoria}/{id}/{titulo}")] that ta interfering on their routes, because, the keys represent variables and were matching with the other routes that has this layout ...

  • I did as described, but keeps returning the same error.

  • Worse than not, I only have 3 routings in this controller, so follow: [Route("sala-de-impresa/noticias/{page?}")] [Route("sala-de-impresa/videos")] [Route("sala-de-impresa/galerias/{page?}")] EDIT In the Noticia controller I have no routing!

  • I edited with the code of the two controllers.

1

The problem was in a conflict between another Controller’s route. My route from the Controller SalaImprensa:

[Route("sala-de-impresa/noticias/{page?}")]

It was conflicting with the Controller’s route Noticia:

[Route("{categoria}/{id}/{titulo}")]

I found with the help of @Ffcdias and solved the problem by adding a name before the parameters of my route in Controller Noticia:

[Route("sala-de-imprensa/{categoria}/{id}/{titulo}")]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.