osman Rahimi
osman Rahimi

Reputation: 1497

Defined Route in mvc returns wrong path

I have these urls :

http://localhost:7708/Product/Search/89737497
http://localhost:7708/Product/Search

for this I set Route Attribute in Action and Controller like this :

[RoutePrefix("Product")]
public partial class ProductController : BaseController
{
    [Route("Search/{categoryCode}")]
    public virtual async Task<ActionResult> Index(int? categoryCode)
    {
    }
}

but I dont send to Index Action , send to GetProductDetail(code) and returns :

The parameters dictionary contains a null entry for parameter 'code' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult GetProductDetail(Int32)'

and i define this , in routeConfig class, but it does not work :

         routes.MapRoute(
           name: "Search",
           url: "Product/Search/{categoryCode}",
           defaults: new { categoryCode = UrlParameter.Optional }
         );

I entered those url in the address bar in browser and it returns that error .

I have this to generate url :

<a href="@Url.Action(MVC.Product.Index(child.Code.ToUrlEncription()))">@child.Name </a>

above code generates this url :

localhost:7708/Product?categoryCode=121212

how can I do this ?

Upvotes: 1

Views: 150

Answers (1)

Ziv Weissman
Ziv Weissman

Reputation: 4526

As for the routes config file you should declare your default action + controller for this route:

routes.MapRoute(
           name: "Search",
           url: "Product/Search/{categoryCode}",
           defaults:  controller = "Product", action = "Index", categoryCode = UrlParameter.Optional
         );

And for custom routes you should make sure your route config has the following code:

public static void RegisterRoutes(RouteCollection routes) {
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    //This will map routes from Route attribute.
    routes.MapMvcAttributeRoutes();

    // ...
}

Upvotes: 1

Related Questions