I am creating a demo application in .net MVC.
Below is the code snippet from my 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");
}
code snippet from RouteConfig :
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
When I hit url http://localhost:54977/student/Edit/1
I am getting following exception.
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
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
.
But it works fine when I hit url http://localhost:54976/student/Edit?StudentId=1
.
I am new to .net MVC. Can anybody please suggest me on this.
Issue is due to your routing configuration.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The third parameter in http://localhost:54977/student/Edit/1 gets mapped to {id} not to studentId.
You have two options to solve the issue:
1) Change your parameter name
public ActionResult Edit(int id) {
var std = studentList.Where(s => s.StudentId == id).FirstOrDefault();
return View(std);
}
2) Add new route for Edit:
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 }
);
Try adding this in your RouteConfig
routes.MapRoute(
"Student", // Route name
"Edit/{StudentId}", // URL with parameters
new { controller = "Student", action = "Edit" } // Parameter defaults
);
Without config routes
$.ajax({
type: "POST",
cache: false,
url: '/Student/Edit/?StudentId='1,
dataType: 'json',
...
...
..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.