MVC Route Parameters Are Null - c#

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

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

Related

MVC Routing Null parameters error

On my Index page I have the following link to the Details view:
#Html.ActionLink("Details", "Details", new { id = item.ClubId })|
My controller is expecting an int:
public ActionResult Details(int ClubId)
{
var club = _service.GetClub(ClubId);
var model = AutoMapper.Mapper.Map<ClubViewModel>(club);
return View(model);
}
Im getting this every time though:
The parameters dictionary contains a null entry for parameter 'ClubId'
of non-nullable type 'System.Int32' for method
'System.Web.Mvc.ActionResult Details(Int32)' in
'MyProject.Web.Controllers.ClubsController'. An optional
parameter must be a reference type, a nullable type, or be declared as
an optional parameter. Parameter name: parameters
I know this is something to do with routing however I have tried swapping UrlParameter.Optional to "" and making the ViewModel's ClubId nullable but the error remains.
If I rewire my controller to accept a Club object and pass in item from the Index view then everything is fine and the ClubId is populated in debug but I'm left with a stupidly large parameter list in the URL.
I don't really get what the problem is here?
Your controller is expecting a parameter named ClubId but you're passing a parameter called id. They need to match.
have you tried using ClubId instead of just id?

Multiple optional parameters routing

I have the following route definition in my webapi project. I have problem one of the parameter is not passed. eg;
when i call /Controller/Action/param2/startdate/enddate the value i passed for param2 is taken for param1 and vice versa.The problem is, the RoutingModule can not detect that the provided route value is for param2 not param1
It works if i use querystring in the url but doesn't want to use querystring. Appreciate your help.
Is there any way to achieve what i expect?
config.Routes.MapHttpRoute(
name: "RetrieveHistory",
routeTemplate: "{controller}/{action}/{param1}/{param2}/{startDate}/{endDate}",
defaults: new
{
controller = "Vend",
action = "RetrieveUtrnHistory",
param1 = RouteParameter.Optional,
param2 = RouteParameter.Optional,
starDate = RouteParameter.Optional,
endDate = RouteParameter.Optional
});
Thanks
To solve your problem you must take into account this things:
you can register more than one route. The first registered route that can handle an URL, will handle it.
you can use something apart from slash / as separator, to make parts of a route distinguishable
you can use parameter constraints, usually regular expressions, to make it easier to discover if a parameter is of one or other kind
you can specify default values for your parameters, and, if you do so, the action method must have default values for them (unless MVC, that only requires them to be nullable or of reference type)
As you didn't tell how your URL looks like I'll show you my own examples.
Let's suppose that you have a TestController Web API Controller class with an action like this:
// GET api/Test/TestAction/ ...
[HttpGet]
public object TestAction(int param1, DateTime startDate, DateTime endDate,
int? param2 = null)
{
return new
{
param1 = param1,
param2 = param2,
startDate = startDate,
endDate = endDate
}.ToString();
}
NOTE: with the default routes a Web API controller's method named GetXxx is available to HTTP GET, a method named PostXxx is available to HTTP POST and so on. However, once you include Controller and Action in the URL template, you must use the [HttpXxx] attributes to make your method available to the required HTTP method.
Optional parameter(s) in the middle
In this first example, I suppose that both param1, and param2 are integer numbers, and stardDate and endDate are dates:
http://myhost/api/Mycontroller/Myaction/12/22/2014-12-01/2014-12-31
http://myhost/api/Mycontroller/Myaction/22/2014-12-01/2014-12-31
If you want the first URL to match parameters like these:
param1 = 12; param2 = 22; startDate = 2014-12-01; endData = 2014-12-31
and the second like these:
param1 = 12; param2 = null; startDate = 2014-12-01; endData = 2014-12-31
You need to register two routes, one that will match each possible URL structure, i.e.
// for the 1st
routeTemplate: "api/{controller}/{action}/{param1}/{param2}/{startDate}/{endDate}"
// for the 2nd
routeTemplate: "api/{controller}/{action}/{param1}/{startDate}/{endDate}"
Note that, in this case, both routes are mutually exclusive, i.e. a single URL can match only one of the routes, so you can register them in any other.
However, you must notice that the second URL doesn't define a value for param2, and the TestAction method requires it. This wouldn't work: you must include a default value for this parameter, both in the controler's method and in the route registration:
action parameter int? param2 = null (C# requires optional parameter to be the last ones).
the route must include the default: defaults: new { param2 = RouteParameter.Optional }
This is the way to solve the optional parameter in the middle problem. In general, you'll need to define several routes, depending on how many optional parameters there are, and declare this parameters, with default values, in the Web API action method.
NOTE: as I wrote above, in MVC you don't need to specify a default value in the method parameter for this to work
Parameter constraints
Specifying constrains for a route parameter has two consequences:
There's a warranty that the parameter value has the expected format
Most importantly, the route will only handle the URL if the format is the expected one. So this helps you make your URL more selective, thus making it more flexible.
You simply need to add a constraint parameter on the route registration, like this:
config.Routes.MapHttpRoute(
name: "Multiparam2",
routeTemplate: "api/{controller}/{action}/{param1}/{param2}/{startDate}/{endDate}",
constraints: new
{
startDate = #"20\d\d-[0-1]?\d-[0-3]?\d", // regex
endDate = #"20\d\d-[0-1]?\d-[0-3]?\d" // regex
},
defaults: new object { }
);
Note that it's necessary to specify a defaults parameter, even if it's empty.
NOTE: the constraints in this case are a regex that only matches dates in the year 20XX, the month expressed as a single digit, or as 0x or 1x, and the date as a single digit or 0x, 1x, 2x or 3x, separated by dashes. So this regex will match 2012-1-1 or 2015-12-30, but not 1920-12-30. You should adapt the regex to your needs.
Optional parameters at the end
By this time I've explained how to support optional parameters, and how to specify formats (constraints) for them, to match a route template.
The usual way to define optional parameters is to do it at the end of the URL template, and, in this case, if there are missing params in a route, they must be all at the end of the route. (Compare this with optional in the middle: they require different routes).
In this example, if you want to make optional the param2, and the startDate and endDate, you must define them in the route registration, and set default parameter values in the action method.
The final code would look like this:
[HttpGet]
public object TestAction(int param1, int? param2 = null, DateTime? startDate = null,
DateTime? endDate = null)
{
return new
{
param1 = param1,
param2 = param2,
startDate = startDate,
endDate = endDate
}.ToString();
}
config.Routes.MapHttpRoute(
name: "Multiparam1",
routeTemplate: "api/{controller}/{action}/{param1}/{startDate}/{endDate}",
constraints: new
{
startDate = #"20\d\d-[0-1]?\d-[0-3]?\d",
endDate = #"20\d\d-[0-1]?\d-[0-3]?\d"
},
defaults: new
{
param2 = RouteParameter.Optional,
startDate = RouteParameter.Optional,
endDate = RouteParameter.Optional
}
);
config.Routes.MapHttpRoute(
name: "Multiparam2",
routeTemplate: "api/{controller}/{action}/{param1}/{param2}/{startDate}/{endDate}",
constraints: new
{
startDate = #"(20\d\d-[0-1]?\d-[0-3]?\d)?",
endDate = #"(20\d\d-[0-1]?\d-[0-3]?\d)?"
},
defaults: new
{
startDate = RouteParameter.Optional,
endDate = RouteParameter.Optional
}
);
Note, that, in this case:
the routes could be mismatched, so they must be registered in the right order, as shown. If you registered first the Multiparam2 route, it would erroneously handle an URL like this: http://localhost:1179/api/test/testaction/1/2014-12-12/2015-1-1, with param1=1; param2="2014-12-12"; startDate="2015-1-1". (You could avoid this with an additional constraint on param2 that only accepts numbers, like param2=#"\d+")
the action must have default values for startDate and endDate.
Conclusions
You can handle default parameters in different positions by carefully:
registering routes in the right order
define default parameters in the route, and also default values in the controller's action
use constraints
If you plan carefully how your routes look like, you can get what you need with a few routes and optional parameters.
JotaBe answer was nice and complete. Just you have to consider if parameters are optional you have to write routeTemplate with the order from lowest parameters to highest.
Just like :
// for the 1st
routeTemplate: "api/{controller}/{action}/{param1}/{startDate}/{endDate}"
// for the 2nd
routeTemplate: "api/{controller}/{action}/{param1}/{param2}/{startDate}/{endDate}"

When I enter localhost/MyController/MyActionName/1 i get a null in the optional parameter why?

SOLUTION
the route
routes.MapRoute(
"Whatever", // Route name
"{controller}/{action}/{id}", //{ID} MUST BE USED IN YOUR CONTROLLER AS THE PARAMETER
new { controller = "MyController", action = "MyActionName", id = UrlParameter.Optional } // Parameter defaults
);
And that's it! I guess you must use the name of the id in the
public actionresult(int id //must be ID HERE like global.asax)
Steps to reproduce my problem:
1. Create a new mvc3 application
2. Go to home controller and put Index(int? x){ return view()}
3. Run the application
4. Go to the url type in the url http://localthost:someport/Home/Index/1
5. Insert a break point in controller to see the value of x
6. Notice that even if you put the url above x NOT equal to 1 as is suppose to!
I just dont understand why i am getting a null in the id....
public ActionResult MyActionName(int? id)
{
//the id is null!!!!!!!!!!!! event thought i just entered the url below!
}
I enter the following url in my browser
http://locahost/MyController/MyActionName/1
//I also put this in my global.asax but it doesnt really help.
routes.MapRoute(
"Whatever", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "MyController", action = "MyActionName", id = UrlParameter.Optional } // Parameter defaults
);
AND!
My error if I put
public ActionResult MyActionName(int id)
{
//the id is null!!!!!!!!!!!! event thought i just entered the url below!
}
Note that the above example was made for simplicity this error is for the actual application.
Server Error in '/' Application.
The parameters dictionary contains a null entry for parameter 'MvrId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Index(Int32)' in 'MedicalVariance.Controllers.MedicineManagementController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: The parameters dictionary contains a null entry for parameter 'MvrId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Index(Int32)' in 'MedicalVariance.Controllers.MedicineManagementController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
Make sure your route is defined before the default route.

What is wrong with my route?

I get the following error when I click the Edit link from the List view
The parameters dictionary contains a null entry for parameter 'envId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'WebUI.Controllers.EnvironmentsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
Here is my code:
Summary.ascx
Routes
Env Controller, Edit Action methods
Env Controller, List Action method
EnvRepository and SqlEnvRepository
Your auto-generated links say this:
<td><%= Html.ActionLink("Edit", "Edit", new { id= Model.EnvironmentID} )%></td>
but the controller code says this:
public ActionResult Edit(int envId)
MVC's model binding hooks the parameters in the action up by name, and the default route assumes the first parameter will be an int called id. Change the name of your Edit() parameter to id and it should work.
Alternatively, you could change the ActionLink parameters object to new { envId = Model.EnvironmentID } but that will cause your URLs to look like this:
http://localhost/Env/Edit?envId = 1
instead of this:
http://localhost/Env/Edit/1

ASP.NET MVC How to correctly map a parameter in url-routing

I have the following route
routes.MapRoute(
"Segnalazioni_CercaSegnalazioni",
"Segnalazioni/CercaSegnalazioni/{flag}",
new { controller = "Segnalazioni", action = "CercaSegnalazioni", flag = 7 }
);
that maps to the following methon of the class SegnalazioniController:
public ActionResult CercaSegnalazioni(int flag)
{
ViewData["collezioneSegnalazioni"] = Models.Segnalazioni.Recupera(flag);
System.Xml.Linq.XElement x = (System.Xml.Linq.XElement)ViewData["collezioneSegnalazioni"];
return View("Index");
}
How come the link http://localhost:1387/Segnalazioni/CercaSegnalazioni/1 gives me the error
The parameters dictionary contains a null entry for parameter 'flag' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult CercaSegnalazioni(Int32)' in 'RecuperoPagatiMvc.Controllers.SegnalazioniController'. To make a parameter optional its type should be either a reference type or a Nullable type.
Nome parametro: parameters
Post all your routes. It sounds like your URL is being handled by a different route than this one. Remember, the order you list your routes does matter. Therefore, if you have another route BEFORE this one that this URL can map to, it will.
MvcContrib contains route debugger. Use it and you'll see which route is called for this url. Here are some instructions how to enable it

Categories

Resources