Tony Trozzo
Tony Trozzo

Reputation: 1231

MVC Route Parameters Are Null

I'm receiving the following error that my default route parameters are null. I've used this same code on a Controller Action that didn't have any parameters in the URL and it worked fine. I know that my custom route is being called but I don't understand why startIndex and pageSize are showing up null in the action.

Error:

The parameters dictionary contains a null entry for parameter 'startIndex' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult ViewVcByStatus(System.String, Int32, Int32)' in 'AEO.WorkOrder.WebUI.Controllers.VendorComplianceController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

Parameter name: parameters

Controller:

public ActionResult ViewVcByStatus(string status, int startIndex, int pageSize) { ... }

Route:

routes.MapRoute("ViewVcByStatus", "ViewVcByStatus/{status}",
  new
  {
    controller = "VendorCompliance",
    action = "ViewVcByStatus",
    startIndex = 0,
    pageSize = WebConfigurationManager.AppSettings["PageSize"],
   });

Link:

<a href="VendorCompliance/ViewVcByStatus?status=PROCESSED">

Also tried this link which produces the same error:

<a href="VendorCompliance/ViewVcByStatus/PROCESSED">

Upvotes: 2

Views: 3496

Answers (2)

Saket Choubey
Saket Choubey

Reputation: 916

Try this.

public ActionResult ViewVcByStatus(string status, int? pageSize, int?startIndex)
    {
        return View();
    }

Route.config

routes.MapRoute(
            name: "ViewVcByStatus",
            url: "ViewVcByStatus/{status}",
            defaults: new { controller = "VendorCompliance", action = "ViewVcByStatus", startIndex = UrlParameter.Optional, pageSize = UrlParameter.Optional });

optional parameters should be declared optional in routeconfig and mark them int? in your action method, This will do the work for you. Hope this helps.This solution will work with your url pattern in your question "http://localhost:53290/VendorCompliance/ViewVcByStatus?status=PROCESSED".

Upvotes: 3

Mikael Puusaari
Mikael Puusaari

Reputation: 1054

Send the startIndex and pageSize with the link(I hardcoded it, use parameters instead), your actionresult is expecting all parameters that the link needs to provide, and the MapRoute will probably fall through to default Route because it can´t match it with any other route matching the one parameter you provided

<a href="VendorCompliance/ViewVcByStatus?status=PROCESSED&startIndex=0&pageSize=0">

Upvotes: 1

Related Questions