Home > OS >  Redirect To Action with ID Parameter - .NetCore Web App MVC
Redirect To Action with ID Parameter - .NetCore Web App MVC

Time:10-23

Need some help trying to redirect to a view.

I have a view/action called Jobs/Index In short, this view grabs a list of employees and I have included a button for each employee to click on so they can view the jobs assigned to them. Each button executes Jobs/EmployeeJobs/Id, the ID depends on their staff ID.

I have a view/action which is jobs/EmployeeJobs/2. This view shows a list of all jobs that are assigned to that staff member with an id of 2, but obviously will change depending on the staff member.

So, on that page I have my EDIT, DETAILS, and DELETE buttons. they're all working fine. However when I try edit some job information and click save. my URL directs me to https://localhost:44327/Jobs.

When a user hits save I want to be redirected back to the view of that staff member such as https://localhost:44327/Jobs/EmployeeJobs/2.

This is my EmployeeJobs/2 Action in my Jobs Controller

     `public async Task<IActionResult> EmployeeJobs(int? id)
    {
                    var jobs = await _context.Jobs
       .Include(j => j.Clients)
       .Include(j => j.Employees)
       .Include(j => j.Stage1)
       .Include(j => j.Stage2)
       .Include(j => j.Substages)
       .Include(j => j.Substages2).Where(m => m.Employees.Id == id)
                   .ToListAsync();


        return View(jobs);

    }`

This is my Edit/5 Action in my Jobs Controller or (POST)

        [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, [Bind("Id,JobNumber,Address,ClientID,StaffId,Notes,Stage1Id,Stage2Id,SubstagesId,Substages2Id,ConceptRequired,ConceptScheduleDate,ConceptSent,RevisionReceived,RevisionCompleted,ConceptApproved,MarketingRequired,MarketingScheduleDate,MarketingSent,MarketingCompleted,RenderRequired,RendererId,RenderSent,RenderReceived,ResourceRequired,PlannerId,ResourceScheduleDate,ResourceSent,ResourceCommentsReceived,ResourceCommentsCompeted,ResourceApproved,WorkingScheduleDate,WorkingCompleted,ReviewCompleted,TrussRequired,TrussId,TrussSent,TrussReceived,EngineerRequired,EngineerId,EngineerSent,EngineerReceived,ClientApprovalSent,ClientApprovalReceived,CouncilSubmission,CouncilId,BCNumber,RFIReceived,RFICompleted,BCGranted,AmendmentRequired,AmendmentScheduleDate,AmendmentCompleted,JobCompleted")] Jobs jobs)
    {
        if (id != jobs.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(jobs);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!JobsExists(jobs.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return RedirectToAction("EmployeeJobs", new { id = id });
           //return RedirectToAction("EmployeeJobs", new RouteValueDictionary(
            //    new { controller = "Jobs", action = "EmployeeJobs", id = id }));

        }

        return View(jobs);
    }

As you can see I have tried two methods multiple times or RedirectToAction. The weird thing is I can get the result I want of showing the jobs assigned to that employee when I am redirected if my code is return RedirectToAction("EmployeeJobs", new { id = 2 });

This code will take me back to the employee that has an ID of 2. So hopefully someone can help me, please go easy on me I'm fairly new to coding

This is the relevant info from my Jobs Model

    public class Jobs
{
    public int Id { get; set; }

    [Display(Name = "Job Number")]
    [Required]
    public int JobNumber { get; set; }

    public string Address { get; set; }

    // FK
    [Display(Name = "Client")]
    [ForeignKey("Clients")]
    public int ClientID { get; set; }

    // FK
    [Display(Name = "Employee")]
    [ForeignKey("Employees")]
    public int StaffId { get; set; }


    public string Notes { get; set; }

    public virtual Clients Clients { get; set; }
    public virtual Employees Employees { get; set; }



}

This is the code from my Employees Model

public class Employees
{
    public int Id { get; set; }

    [Display(Name = "First Name")]
    [RegularExpression(@"^[A-Z] [a-zA-Z\s]*$")]
    [StringLength(20, MinimumLength = 3)]
    [Required]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    [RegularExpression(@"^[A-Z] [a-zA-Z\s]*$")]
    [StringLength(20, MinimumLength = 3)]
    [Required]
    public string LastName { get; set; }

    [Display(Name = "Contact Number")]
    [StringLength(15, MinimumLength = 8)]
    [Required]
    public string ContactNumber { get; set; }

    [StringLength(80, MinimumLength = 3)]
    [Required]
    public string Email { get; set; }
}

CodePudding user response:

You said if you hard code the Id like the following then it is working:

return RedirectToAction("EmployeeJobs", new { id = 2 });

Then try this:

return RedirectToAction("EmployeeJobs", "Jobs", new { id = jobs.Id });

CodePudding user response:

try returning an empty view without necessarily passing an argument to it like so

 return View(); 

CodePudding user response:

I think you have the error in you Index action, when you are quering db. This is why it can't return new view. You are mixing employeeId with jobId. For id=2 you have an employee with Id =2 , so why it is working only for id=2;

And your index action has a very confusing query, and it is not async.

Try this

 var jobs = await _context.Jobs
       .Include(j => j.Clients)
       .Include(j => j.Employees)
       .Include(j => j.Stage1)
       .Include(j => j.Stage2)
       .Include(j => j.Substages)
       .Include(j => j.Substages2)
       .Where(m =>  m.Employees.Id == id)
       .ToListAsync();

 return View(jobs);

but I was wondering how this could be even compiled

  .Include(j => j.Employees)
      .....
  .Where(m =>  m.Employees.Id == id)

Is Employees one person?

UPDATE

After seeing your Job class I think your where is ok, but you can use this too

 .Where(m =>  m.StaffId == id)

and fix your Edit action

 return RedirectToAction("EmployeeJobs", new { id = job.StaffId });

now it should be working

  • Related