Reputation: 634
I've been working on a MVC4 C# App and send via link a value to a controller this way
<a href="@Url.Action("MyAction", "Home", new { Id = @ViewBag.id})">@ViewBag.option2</a>
and works just fine but now I need to send three values via the same link to the same controller and have verified the values are not null
<a href="@Url.Action("MyAction", "Home", new { Id = @ViewBag.id, Id2 = @ViewBag.grupo, Id3 = @ViewBag.correlativo })">@ViewBag.option2</a>
but get the next error
Message = The parameters dictionary contains a null entry for parameter 'grupo' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult ModificarOrdenInicioFormulario(System.String, Int32, Int32)' in 'GFC_Site.Controllers.HomeController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
this is the action in my Home controller
public ActionResult MyAction(string Id, Int32 grupo, Int32 correlativo)
and this is my RouteConfig
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
could you please tell me what to add or where the error is?
Upvotes: 0
Views: 4252
Reputation: 218702
Your current code is generating the href attribute value for the link like this
Home/MyAction/10?id2=123&id3=456
But your action method parameters are Id
, grupo
and correlativo
.
Your action method parameter name should match with your route value dictionary keys.
Use grupo
and correlativo
as the route value item keys instead of id2
and id3
<a href="@Url.Action("MyAction", "Home",
new { Id = @ViewBag.id,
grupo = @ViewBag.grupo,
correlativo = @ViewBag.correlativo })">@ViewBag.option2</a>
This will generate the href
attribute value like this, which has the proper querystring keys matching with the action methor parameter name
Home/MyAction/10?grupo=123&correlativo=456
This should work, assuming your ViewBag items has valid (non null)numeric values set to it. If those could be null, consider changing your action method parameter from int
to nullable int (int?
)
The route value 10
in the url will be automatically mapped to the parameter named Id
because we defined that in the default route pattern registered in the RegisterRoutes
method.
Upvotes: 2
Reputation: 831
<a href="@Url.Action("MyAction", "Home", new
{
Id = @ViewBag.id,
grupo = @ViewBag.grupo,
correlativo = @ViewBag.correlativo
})">@ViewBag.option2</a>
Your parameter name must be same.To handle null case s you can change your action signature as public ActionResult MyAction(string Id, Int32? grupo, Int32? correlativo)
Upvotes: 1