我是新来这里学习MVC的。我遇到了这个错误,找不到解决方案。
我的 Controller 看起来像这样:
public class EmployeeDataController : Controller
{
public ActionResult Details(int idd)
{
EmployeeDataContext edc = new EmployeeDataContext();
EmployeeData employee= edc.employeedata.Single(emp => emp.id == idd);
return View(employee);
}
}
当从浏览器(即 http://localhost:4166/EmployeeData/details/1)执行 Details 方法时,我得到这个错误:
The parameters dictionary contains a null entry for parameter 'idd' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Details(Int32)' in 'MvcDemo1.Controllers.EmployeeDataController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
任何帮助都会很好地解决我的问题。
当我更新代码并尝试编译程序时,编译时没有错误,但是当我运行程序时出现错误
EmployeeData employee= edc.employeedata.Single(x=>x.id==id);
**在 EntityFramework.SqlServer.dll 中出现类型为“System.Data.Entity.Core.EntityCommandExecutionException”但未在用户代码中处理的异常
附加信息:执行命令定义时发生错误**
最佳答案
当您访问 EmployeeData/details/1
等 URL 时,MVC 将使用您的路由来映射要使用的 Controller 、操作方法和参数。默认情况下,您将拥有的路线如下所示:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
对于您的 URL,这表示将 EmployeeData
作为 Controller ,将 details
作为操作方法,将 1
作为值名称为 id
的可选参数。您的参数称为 idd
因此未映射。由于该参数被标记为可选,但它在您的 Details
方法中不可为 null,因此会发生异常。
你有三种方法来解决这个问题。
首先,您可以更改路由以使用 idd
而不是 id
:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{idd}",
defaults: new { controller = "Home", action = "Index", idd = UrlParameter.Optional }
);
其次,您可以将 Details
方法中的参数更改为 id
:
public ActionResult Details(int id)...
最后,您可以将正在使用的 URL 更改为在发送的参数中显式显示:
localhost:4166/EmployeeData/details?idd=1
关于c# - 参数字典包含不可为空类型 'idd' 的参数 'System.Int32' 的空条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30191256/