.netMVCでデモアプリケーションを作成しています。
以下は私のStudentControllerからのコードスニペットです。
public ActionResult Edit(int studentId)
{
var std = studentList.Where(s => s.StudentId == studentId).FirstOrDefault();
return View(std);
}
[HttpPost]
public ActionResult Edit(Student std)
{
//write code to update student
return RedirectToAction("Index");
}
RouteConfigのコードスニペット:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
URLhttp://localhost:54977/student/Edit/1
を押すと、次の例外が発生します。
The parameters dictionary contains a null entry for parameter 'studentId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'MVC1.Controllers.StudentController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
。
しかし、URLを押すと正常に動作しますhttp://localhost:54976/student/Edit?StudentId=1
。
.netMVCは初めてです。誰かがこれについて私に提案できますか?
問題はルーティング構成が原因です。
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
http:// localhost:54977 / student / Edit / 1の3番目のパラメーターは、studentIdではなく{id}にマップされます。
この問題を解決するには、次の2つのオプションがあります。
1)パラメータ名を変更します
public ActionResult Edit(int id) {
var std = studentList.Where(s => s.StudentId == id).FirstOrDefault();
return View(std);
}
2)編集用の新しいルートを追加します。
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"EditStudent",
"Edit/{StudentId}",
new { controller = "Student", action = "Edit" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加