简体   繁体   中英

An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. What to do?

public ActionResult Applicant(int JobPostId)
{
    List<JobSeeker> jobSeekers = new List<JobSeeker>();
    var ApplicationList = db.JobApplications.Where(x => x.JobPostId == JobPostId).ToList();

    foreach(JobApplication app in ApplicationList)
    {
        jobSeekers.Add(db.Users.OfType<JobSeeker>().Single(x => x.Id == app.JobSeekerId));
    }
    // var JobseekerForJobPost = db.Users.OfType<JobSeeker>().Where(x => x.JobPostsAppliedFor.Any(y => y.JobPostID == JobPostId)).ToList();

    return View(jobSeekers);
}

@Html.ActionLink("View Applicants", "Applicant", new { id = item.JobPostID }) |


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 }
    );
}

I cannot figure it out why it is giving me error.

Your action method has a value type parameter (an int ):

public ActionResult Applicant(int JobPostId)

But you're not supplying the route with a value for it:

Html.ActionLink("View Applicants", "Applicant", new { id = item.JobPostID })

The error is telling you that you must supply a value for that parameter, because an int can't otherwise be null . If you want this value to possibly be null , make it nullable:

public ActionResult Applicant(int? JobPostId)

Or, if it shouldn't be nullable, provide a value for it:

Html.ActionLink("View Applicants", "Applicant", new { JobPostID  = item.JobPostID })

(From your usage of that value in that action method, it looks like it shouldn't be null . But I suppose it's possible that it could be in your data.)


Side note: By C# convention variables should be lowecase:

public ActionResult Applicant(int jobPostId)

and:

Html.ActionLink("View Applicants", "Applicant", new { jobPostID  = item.JobPostID })

Just make your parameter

public ActionResult Applicant(int JobPostId)

optional

public ActionResult Applicant(int? JobPostId)

In the routing it's mapped as optional thats why you have to make it nullable

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM