可选参数必须是引用类型 MVC4 C#

我一直在研究 MVC4 C# 应用程序,并通过这种方式通过链接将值发送到控制器


<a href="@Url.Action("MyAction", "Home", new { Id = @ViewBag.id})">@ViewBag.option2</a>

并且工作得很好,但现在我需要通过相同的链接将三个值发送到同一个控制器并验证这些值不为空


<a href="@Url.Action("MyAction", "Home", new { Id = @ViewBag.id, Id2 = @ViewBag.grupo, Id3 = @ViewBag.correlativo })">@ViewBag.option2</a>

但得到下一个错误


消息 = 参数字典在“GFC_Site.Controllers”中包含方法“System.Web.Mvc.ActionResult ModificarOrdenInicioFormulario(System.String, Int32, Int32)”的不可为空类型“System.Int32”的参数“grupo”的空条目.HomeController'。可选参数必须是引用类型、可为空类型或声明为可选参数。参数名称:参数


这是我的 Home 控制器中的动作


public ActionResult MyAction(string Id, Int32 grupo, Int32 correlativo)

这是我的 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 }

        );

    }

}

你能告诉我要添加什么或错误在哪里吗?


缥缈止盈
浏览 248回答 2
2回答

蛊毒传说

您当前的代码正在为这样的链接生成 href 属性值Home/MyAction/10?id2=123&id3=456但是您的操作方法参数是Id,grupo和correlativo。您的操作方法参数名称应与您的路由值字典键匹配。使用grupoandcorrelativo作为路由值项键而不是id2andid3<a href="@Url.Action("MyAction", "Home",&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;new { Id = @ViewBag.id,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;grupo = @ViewBag.grupo,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;correlativo = @ViewBag.correlativo })">@ViewBag.option2</a>这将生成这样的href属性值,它具有与操作方法参数名称匹配的正确查询字符串键Home/MyAction/10?grupo=123&correlativo=456这应该有效,假设您的 ViewBag 项目设置了有效(非空)数字值。如果这些可能为空,请考虑将您的操作方法参数从int可空 int ( int?)10url 中的路由值将自动映射到命名的参数,Id因为我们在RegisterRoutes方法中注册的默认路由模式中定义了该参数。

吃鸡游戏

<a href="@Url.Action("MyAction", "Home", new&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Id = @ViewBag.id,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;grupo = @ViewBag.grupo,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;correlativo = @ViewBag.correlativo&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })">@ViewBag.option2</a>您的参数名称必须相同。要处理 null case,您可以将操作签名更改为 public ActionResult MyAction(string Id, Int32? grupo, Int32? correlativo)
打开App,查看更多内容
随时随地看视频慕课网APP