Question

Ok this is driving me nuts. My client is on MVC 2 (yes I know) and wants a few more actions added to their existing application.

If I put in the URL of:

http://10.211.55.3/Templates/

it works as expected and comes up with the default action. However if I put in:

http://10.211.55.3/Templates/GetTemplateDetails/1

I get this error:

The parameters dictionary contains a null entry for parameter 'TemplateID' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult GetTemplateDetails(Int32)'. To make a parameter optional its type should be either a reference type or a Nullable type. Parameter name: parameters

As far as I can tell, I'm supplying the correct route pattern and still it doesn't seem to work. Looking at their Global.asax they have what one would expect:

routes.AddCombresRoute("Combres Route");
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("favicon.ico");
routes.MapRoute(
    "Default", // Route name
    {controller}/{action}/{id}", // URL with parameters
    new {controller = "Home", action = "Index", id = 0} // Parameter defaults
);
routes.MapRoute(
    "MarketingRoute",
    "Marketing/{action}/{routingAction}/{token}",
    new
    {
        controller = "Marketing",
        action = "Route",
        routingAction = string.Empty,
        token = string.Empty
    });

..and here's the test action on the controller which doesn't work....

public ActionResult Index()
{
    return View();
}

[AcceptVerbs(HttpVerbs.Get)]
[ActionName("GetTemplateDetails")]
public ActionResult GetTemplateDetails(int TemplateID)
{
    return View();
}

Really hoping a fresh pair of eyes can help see what I'm obviously overlooking here.

Était-ce utile?

La solution

First Workaround is to mark the argument as optional Mark TemplateID as nullable

public ActionResult GetTemplateDetails(int? TemplateID)
    {

        return View();
    }

Second Way

 public ActionResult GetTemplateDetails([Bind(Prefix="id")] int TemplateID)
        {

            return View();
        }

Autres conseils

The parameter on your controller method should be named id. The ModelBinder looks for a parameter named TemplateID but since the default parameter(the one in the url) is named id, it never finds it.

Just change it to this:

public ActionResult GetTemplateDetails(int id)
{
    return View();
} 

When you define your route like

routes.MapRoute(
    "Default", // Route name
    {controller}/{action}/{id}", // URL with parameters
    new {controller = "Home", action = "Index", id = 0} // Parameter defaults
);

and try to access any method with a not null parameter like int TemplateID then you have to pass a value for the parameter likehttp://10.211.55.3/Templates/GetTemplateDetails/?TemplateID=1 but if your parameter is named as id then the mapping option automatically provides a value to the parameter and you don't get any error.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top