Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net-mvc

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.

like image 689
Rohit Waghela Avatar asked Jul 12 '17 13:07

Rohit Waghela


Video Answer


1 Answers

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 }
        );
like image 102
Jayakrishnan Avatar answered Oct 03 '22 22:10

Jayakrishnan