Ami*_*mar 44 c# asp.net-mvc asp.net-mvc-4
我是新来的MVC.在我的应用程序中,我正在从Mydatabase中检索数据.但是当我运行我的应用程序时,它显示错误,这是我的网址
http://localhost:7317/Employee/DetailsData/4
  Exception Details: System.ArgumentException: The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult DetailsData(Int32)' in 'MVCViewDemo.Controllers.EmployeeController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
这是我的web.config文件代码
<connectionStrings>
  <add name="EmployeeContext" connectionString="Server=.;Database=mytry;integrated security=true; ProviderName=System.Data.SqlClient"/>
</connectionStrings>
这是我的员工模型类(Employee.cs)
[Table("emp")]    /* to map tablename with our class name*/
    public class Employee
    {
        public int EmpId { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string City { get; set; }
    }
我的EmployeeContext.cs Model类
 public class EmployeeContext:DbContext
    {
        public DbSet<Employee> Employees { get; set; }
    }
我的EmployeeController.cs
 public ActionResult DetailsData(int k)
        {
            EmployeeContext Ec = new EmployeeContext();
            Employee emp = Ec.Employees.Single(X => X.EmpId == k);           
            return View(emp);
        }
和我的看法
<h2>DetailsData</h2>
@Model.Name<br />
@Model.City<br />
@Model.Gender<br />
@Model.EmpId
Dis*_*ile 75
您似乎使用的默认路由定义如下:
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
这条路线的关键部分是这{id}件作品.如果您查看您的操作方法,则k代替您的参数id.您需要将操作方法更改为此方法,以使其与route参数匹配:
// change int k to int id
public ActionResult DetailsData(int id)
如果您想将参数保留为k,那么您可以将URL更改为:
http://localhost:7317/Employee/DetailsData?k=4
您的连接字符串似乎也有问题.在您的web.config中,您需要将连接字符串更改为此(由haim770在他删除的另一个答案中提供):
<connectionStrings>
  <add name="EmployeeContext"
       connectionString="Server=.;Database=mytry;integrated security=True;"
       providerName="System.Data.SqlClient" />
</connectionStrings>
您的操作似乎需要k但ModelBinder无法找到它(从表单,请求或查看数据或..)将您的操作更改为:
public ActionResult DetailsData(int? k)
    {
        EmployeeContext Ec = new EmployeeContext();
        if (k != null)
        {
           Employee emp = Ec.Employees.Single(X => X.EmpId == k.Value);
           return View(emp);
        }
        return View();
    }
| 归档时间: | 
 | 
| 查看次数: | 115974 次 | 
| 最近记录: |