user3788671
user3788671

Reputation: 2047

Action getting a null parameter C# MVC 4

When I debug through my code, I can see the results have data stored but when it reaches the Results action...results is null. Why is this happening? The default action gets the right parameter and comes up with the correct results but I am having trouble passing the results list in my Default action as a paramter to my Results action.

[HttpGet]
public ActionResult Default()
{
    var currentUserCono = GetCurrentUserCono();

    //Set the Viewbags to populate the drop down menus on the view
    ViewBag.CompanyList = SelectListLib.GetCompanies(currentUserCono);
    ViewBag.BranchList = SelectListLib.GetBranches(currentUserCono);
    ViewBag.StatusTypeList = SelectListLib.GetStatusTypes();

    return View();
}

[HttpPost]
public ActionResult Default(int cono, string firstName, string lastName, string branch, string salesRep, bool statustype)
{
    //Query the Search Options with the database and return the matching results to the Results Page.
    var results = EmployeeDb.EmployeeMasters.Where(e => e.StatusFlag == statustype);

    results = results.Where(e => e.CompanyNumber == cono);
    if (!branch.IsNullOrWhiteSpace())
    {
        results = results.Where(e => e.Branch == branch);
    }
    if (!firstName.IsNullOrWhiteSpace())
    {
        results = results.Where(e => e.FirstName == firstName);
    }
    if (!lastName.IsNullOrWhiteSpace())
    {
        results = results.Where(e => e.LastName == lastName);
    }

    return RedirectToAction("Results", "Employee", routeValues: new { results = results.ToList() });

    // results has data in it 
}

[HttpGet]
public ActionResult Results(List<Models.EmployeeMaster> results)
{
    // results is equal to null
    return View(results);
}

Upvotes: 0

Views: 731

Answers (1)

WeSt
WeSt

Reputation: 2684

This question was already answered in this StackOverflow question. A RedirectToAction is not working as a normal method call, but instead as a HTTP redirect (see the other link for more details). You could either use TempData or invoke the method directly:

[HttpPost]
public ActionResult Default(int cono, string firstName, string lastName, string branch, string salesRep, bool statustype)
{
    //Query the Search Options with the database and return the matching results to the Results Page.
    var results = EmployeeDb.EmployeeMasters.Where(e => e.StatusFlag == statustype);

    results = results.Where(e => e.CompanyNumber == cono);
    if (!branch.IsNullOrWhiteSpace())
    {
        results = results.Where(e => e.Branch == branch);
    }
    if (!firstName.IsNullOrWhiteSpace())
    {
        results = results.Where(e => e.FirstName == firstName);
    }
    if (!lastName.IsNullOrWhiteSpace())
    {
        results = results.Where(e => e.LastName == lastName);
    }

    return Results(results.ToList()); 
}

Upvotes: 3

Related Questions