MVC Routing Null parameters error - c#

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?

Related

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

How to pass the parameter to a method when calling in MVC5?

I have a method defined like this:
public ActionResult MatchedBusinesses(List<Business> businesses)
{
if (businesses != null)
{
return View(businesses);
}
return View("NoMatchFound");
}
Then, in my other method I have something similar to this one:
var list = results.AsEnumerable().OrderBy(b => Math.Abs(Convert.ToInt32(temp) - Convert.ToInt32(b.Zip))).Take(5).ToList();
return RedirectToAction("MatchedBusinesses", "Home", list);
The point is that, for the list variable I get the 5 entries that I select using the query. But, then I want to pass that result to my other method, which will be used in other method's view. The problem is, when I call the other method, the businesses parameter is always null. How can I solve the problem? Clearly, I'm not passing the parameter to my MatchedBusinesses method correctly. Any idea, how to solve the problem?
You are using the overload of RedirectToAction where the 3rd parameter is object routeValues. Internally the method uses reflection to build the route values based on the names and the ToString() values of the objects properties.
It works only for properties that are value types, but for properties that are complex types, including collections, it will not bind because (in your case) the value is a string "List<YourAssembly.Business>" and a string cannot be bound to a collection.
You need to persist the collection before redirecting (e.g. database, session, TempData) and then retrieve the collection in the action result.
For example
var list = results.AsEnumerable()....
TempData["results"] = list;
return RedirectToAction("MatchedBusinesses", "Home");
public ActionResult MatchedBusinesses()
{
List<Business> businesses = (List<Business>)TempData["results"];
}
but use TempData with caution (if the user refreshes the browser, the data will be lost). Its better to persist the information to the database with some key, and then pass the key as a route parameter to the MatchedBusinesses() method so that you can retrieve the data from the database.
Edit
What you're trying to do doesn't make much sense. You cannot, and should not, attempt to send large and/or complex objects, like a List, using Route. Instead you should use POST, or follow Stephen Muecke's suggestion in using TempData
However, here's how you can correctly send simple values using RouteValue
You pass parameters by using
return RedirectToAction("ActionName", "ControllerName",
new { paramName = paramValue });
Or if the target Action it's in the same controller
return RedirectToAction("ActionName", new { paramName = paramValue });
The parameter name, is optional. But using
return RedirectToAction("ActionName", new { paramName = paramValue });
Implies that the target action accepts a parameter with the name paramValue.
Here are all the overloads for RedirectToAction
http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.redirecttoaction%28v=vs.118%29.aspx
Try wrapping your parameter in your return statement in a blank object variable like so:
return RedirectToAction("MatchedBusinesses", "Home", new { businesses = list });
All of the route values for an action have to be one parameter, so it's passed as an object, and then split into the various parameters of the receiving action. Even if you have only one param, it's still looking for an object to split.

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