c# - "The parameters dictionary contains a null entry for parameter"- 如何修复?

标签 c# asp.net asp.net-mvc

我正在尝试实现一个编辑页面,以便管理员修改数据库中的数据。不幸的是,我遇到了一个错误。

下面的代码:

public ViewResult Edit(int productId) {
       // Do something here 
}

但是我收到这个错误:

"The parameters dictionary contains a null entry for parameter 'productId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ViewResult Edit(Int32)' in 'WebUI.Controllers.AdminController'. To make a parameter optional its type should be either a reference type or a Nullable type.
Parameter name: parameters"

我在 Global.asax.cs 中更改了我的路线,如下所示:

 routes.MapRoute(
"Admin",
"Admin/{action}/{ productId}",
new { controller = "Admin", action = "Edit",  productId= "" }
);

但我仍然收到错误。

最佳答案

productId 的空字符串(在您的默认路由中)将被框架解析为空条目,并且由于 int 不允许 null...您遇到错误。

改变:

public ViewResult Edit(int productId)

public ViewResult Edit(int? productId)

如果您想让调用者不必传入产品 ID,根据路由的配置方式,这就是您想要执行的操作。

您还可以重新配置您的默认路由,以便在没有提供 productId 时传入一些已知的默认值:

routes.MapRoute( 
    "Admin", 
    "Admin/{action}/{ productId}", 
    new { controller = "Admin", action = "Edit",  productId= -1 } 

关于c# - "The parameters dictionary contains a null entry for parameter"- 如何修复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2500021/

相关文章:

asp.net - 在 asp.net mvc 中使用 wkhtmltopdf 需要很长时间才能启动

c# - jquery 中的 if 语句不起作用

c# - 获得 List<object> 之间差异的最快方法

c# - MVC RedirectToAction 在 JSON 后返回后不起作用

C# 编程作业

.net - 如何打破这个字符串并按版本号排序

c# - 从数据库检索数据但没有值时如何获取错误消息

javascript - 服务器和浏览器日期差异

c# - 为什么这个 C# 转换示例不起作用?

c# - NHibernate 无法将 MySQL 日期/时间值转换为 System.DateTime