可选参数必须是引用类型,可为空的类型,或者必须声明为可选参数。该怎么办?

时间:2018-12-09 15:05:42

标签: c#

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

我无法弄清楚为什么它会给我带来错误。

2 个答案:

答案 0 :(得分:3)

您的操作方法具有值类型参数(int):

public ActionResult Applicant(int JobPostId)

但是您没有为路由提供值:

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

错误告诉您必须提供该参数的值,因为否则int不能为null。如果您希望此值可能为null,则使其可为空:

public ActionResult Applicant(int? JobPostId)

或者,如果它不应为空,则为其提供一个值:

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

(根据您在该操作方法中使用该值的情况,它看起来不应null。但是我认为它是可能可能在您的数据中。)


侧面说明:根据C#约定,变量应为小写字母:

public ActionResult Applicant(int jobPostId)

和:

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

答案 1 :(得分:0)

只需设置您的参数

public ActionResult Applicant(int JobPostId)

可选

public ActionResult Applicant(int? JobPostId)

在路由中,它被映射为可选,这就是为什么必须使其为空的原因