An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters`

Viewed 23927

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.

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.

3 Answers

Without config routes

  $.ajax({
                type: "POST",
                cache: false,
                url: '/Student/Edit?StudentId='1,
                dataType: 'json',
                ...
                ...
                ..
Related