1. ホーム
  2. c#

[解決済み] MVC : パラメータ辞書に、非 null 型 'System.Int32' のパラメータ 'k' の null エントリが含まれています。

2022-02-26 12:59:30

質問

を始めたばかりです。 MVC . 私のアプリケーションでは、データベースからデータを取得しています。しかし、私のアプリケーションを実行すると、次のようなエラーが表示されます。 これは私のURLです

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 モデルクラス

 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

解決方法は?

このように定義されたデフォルトルートを使用しているようです。

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

そのルートで重要なのは {id} の部分です。アクションメソッドを見てみると、パラメータは k ではなく id . アクションメソッドをこれに変更し、ルートパラメータと一致するようにする必要があります。

// 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>