参数字典包含非可空类型'System.Int32'的参数'did'的空条目

时间:2015-08-20 15:22:53

标签: c# asp.net-mvc

参数字典包含'MvcApplication1.Controllers.EmployeeController'中方法'System.Web.Mvc.ActionResult Index(Int32)'的非可空类型'System.Int32'的参数'did'的空条目。可选参数必须是引用类型,可空类型,或者声明为可选参数。 我不知道从什么这个例外,但我搜索更多但仍未达到解决此错误可以帮助我,如果你可以。

  public class EmployeeContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
    public DbSet<Department> Depts { get; set; }
}


[Table("tblDepartment")]
public class Department
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }     
    public List<Employee> employeees { get; set; }

}
  [Table("TblEmployees")]
public class Employee
{
    [Key]
    public int EmployeeId { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
    public string Gender { get; set; }
    public int DepartmentId { get; set; }

}


public ActionResult Index(int id)
    {
        EmployeeContext emp = new EmployeeContext();

        var employ = emp.Employees.Where(empp => empp.DepartmentId == id).ToList();

         return View(employ);
    }





@using MvcApplication1.Models;

@model IEnumerable<Department>

@{
    ViewBag.Title = "departments";
}

<div>
    <h2>departments</h2>
    <ul>
        @foreach (Department department in @Model)
        {
            <li>@Html.ActionLink(department.Name,"Index", "Employee", new { id = department.ID }, null)</li>

        }

    </ul>
</div>

@model IEnumerable<MvcApplication1.Models.Employee>
@using MvcApplication1.Models;

@{
    ViewBag.Title = "EmployeeList";
}
<div>
    <h2>EmployeeList</h2>
    <ul>
        @foreach (Employee emp in @Model)
        {
            <li>@Html.ActionLink(emp.Name, "Details", new { id = emp.EmployeeId })</li>
        }

    </ul>
    @Html.ActionLink("Back to Department List", "Index", "Department")

</div>

 public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");          

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = ""}
        );
    }

1 个答案:

答案 0 :(得分:2)

您有以下路线:

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = ""}
        );

id参数不是可选的,因此您调用的任何操作都没有此参数的值,您可以将id参数定义为可选:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional}
);