简体   繁体   中英

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">

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 ".

发送带有链接的startIndex和pageSize(我将其硬编码,改用参数),您的actionresult期望该链接需要提供的所有参数,并且MapRoute可能会陷入默认Route,因为它无法与任何路径匹配与您提供的一个参数匹配的其他路线

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

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