Reputation: 39
I am new here to learn MVC. I struck on this error, I couldn't find the solution.
My Controller Look like this:
public class EmployeeDataController : Controller
{
public ActionResult Details(int idd)
{
EmployeeDataContext edc = new EmployeeDataContext();
EmployeeData employee= edc.employeedata.Single(emp => emp.id == idd);
return View(employee);
}
}
When executing the Details method from the browser (i.e. http://localhost:4166/EmployeeData/details/1) I get this error:
The parameters dictionary contains a null entry for parameter 'idd' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Details(Int32)' in 'MvcDemo1.Controllers.EmployeeDataController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
Any help would be great to solve my problem.
When i update my code and try to compile the program, there is no error at compile time but when i run the program that time i got an error
EmployeeData employee= edc.employeedata.Single(x=>x.id==id);
**An exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: An error occurred while executing the command Definition **
Upvotes: 3
Views: 3723
Reputation: 12815
When you visit a URL such as EmployeeData/details/1
, MVC will use your routes to map the controller, action method and parameters to use. By default the route you will have will look something like this:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
With your URL, this says to take the EmployeeData
as the controller, details
as the action method and 1
as the value for the optional parameter with the name id
. Your parameter is called idd
so it's not mapped. As the parameter is marked as optional but it's non-nullable in your Details
method an exception occurs.
You have three ways of solving this.
Firstly, you could change your route to use idd
instead of id
:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{idd}",
defaults: new { controller = "Home", action = "Index", idd = UrlParameter.Optional }
);
Secondly, you could change the parameter in your Details
method to be called id
:
public ActionResult Details(int id)...
Finally, you could change the URL you are using to be explicit in the parmater being sent:
localhost:4166/EmployeeData/details?idd=1
Upvotes: 5
Reputation: 2421
If you are using default route config - than simply rename your action parameter to id
:
public ActionResult Details(int id)
{
EmployeeDataContext edc = new EmployeeDataContext();
EmployeeData employee = edc.employeedata.Single(emp=>emp.id == id);
return View(employee);
}
Your parameter name id
should exactly match one in the route config.
Upvotes: 3