I'm facing a problem that I couldn't solve. I get this message on my browser:
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Students(Int32)' in 'FirstProject.Controllers.HomeController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
I will give you the codes that I see related to the problem:
RouteConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace FirstProject
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
HomeController.cs
using FirstProject.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FirstProject.Controllers
{
public class HomeController : Controller
{
level_8_coursesEntities db = new level_8_coursesEntities();
public ActionResult Index()
{
List<level_8_courses> list = db.level_8_courses.ToList();
return View(list);
}
public ActionResult Numberofstudents()
{
List<level_8_courses> list = db.level_8_courses.ToList();
return View(list);
}
public ActionResult Students(int id)
{
List<student> studentlist = db.students.Where(x => x.corId == id).ToList();
return View(studentlist);
}
Students
@using FirstProject.Models;
@model List<student>
@foreach (var item in Model)
{
<p>@item.sName</p>
}
I do not have enough experience in programming, so please explain in detail what I do in each file and what I write.
Thank you very much.
CodePudding user response:
The action method public ActionResult Students(int id)
is declared with parameter id
as int
type, but you hit this method with non-number value.
For example, you can change the method signature, like below:
public ActionResult Students(int? id)
{
List<student> studentlist = null;
if (id.HasValue)
{
studentlist = db.students.Where(x => x.corId == id).ToList();
}
else
{
// Set the `studentlist` to some default value when `id` doesn't defined or not a number.
studentlist = ...
}
return View(studentlist);
}