Understanding Optional and Compulsory Parameters
If the MVC Framework cannot find a value for a reference type parameter (such as a string or object), the action
method will still be called, but using a null value for that parameter. If a value cannot be found for a value type parameter (such
as int or double), then an exception will be thrown, and the action method will not be called. Here is another way to think
about it:
Value-type parameters are compulsory. To make them optional, either specify a default value (see the next section) or
change the parameter type to a nullable type (such as int? or DateTime?), so the MVC Framework can pass
null if no value is available.
值类型可以指定默认值,或指定值类型可以为null。
public ActionResoult Index(int ? Age,string Name)
or
public ActionResoult Index(int Age = 18 , string Name = "jack")
应验证数据是否为null。
如果值无法转换为指定类型,ModelState将置为false。
Reference-type parameters are optional. To make them compulsory (to ensure that a non-null value is passed), add
some code to the top of the action method to reject null values. For example, if the value equals null, throw an
ArgumentNullException.
引用类型应验证数据是否为null。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】博客园2025新款「AI繁忙」系列T恤上架,前往周边小店选购
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步