MVC如何避免控制器方法接收到的值不能被转换为参数类型

假设控制器方法参数类型是int:

public ActionResult GetSth(int id)
        {
            return Content(id.ToString());
        }

而视图传递过来的是字符串:

@Html.ActionLink("获取","GetSth",new {id="hello"})

于是就会报类似如下的错:       

对于“MvcApplication3.Controllers.HomeController”中方法“System.Web.Mvc.ActionResult GetSth(Int32)”的不可以为 null 的类型“System.Int32”的参数“id”,参数字典包含一个 null 项。可选参数必须为引用类型、可以为 null 的类型或声明为可选参数。
参数名: parameters

 

解决方法一:允许参数可以为null

public ActionResult GetSth(int? id)
        {
            return Content(id.ToString());
        }

解决方法二:给参数赋默认值

public ActionResult GetSth(int id=1)
        {
            return Content(id.ToString());
        }
原文地址:https://www.cnblogs.com/darrenji/p/3798330.html