Ronald McDonald
Ronald McDonald

Reputation: 2911

Wrong view being returned for controller method

I have a controller method that is returning the wrong view. The view I have is the same name as the controller method "AssignTask.cshtml". The method is "public virtual ActionResult AssignTask(ManageTaskModel model) "

Can anyone see what I'm doing wrong?

[HttpGet]
public virtual ActionResult ManageTasks()
{
    try
    {
        var model = new ManageTaskModel ();
        model.assignedPSUsers = Orchestrator.GetAssignedPSUsers();
        return View(model);
    }
    catch (Exception e)
    {
        ModelState.AddModelError("ErrorMsg", e.Message);
    };

    return this.RedirectToAction("Index");
}

[HttpPost]
public virtual ActionResult ManageTasks(ManageTaskModel model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }
    try
    {   //User has seleced the user that they want to see Tasks for
        if (model.selectedUser != null && model.newUser==null)
        {
            model.assignedPSUsers = Orchestrator.GetAssignedPSUsers();
            model.FcvsTaskList = Orchestrator.GetTasksForAssignedPSUser(model.selectedUser);

            return AssignTask(model);
        }

    }
    catch (Exception e)
    {
        ModelState.AddModelError("ErrorMsg", e.Message);
        return View(model);
    }
    return this.RedirectToAction("Index");

}

[HttpGet]
public virtual ActionResult AssignTask(ManageTaskModel model) 
{ 
    if (model.selectedUser != null && model.newUser == null)
    {


        **return View(model);**  //returning the ManageTask instead of AssignTask View

    }

    return this.RedirectToAction("Index");
}

Upvotes: 1

Views: 1440

Answers (2)

Andrzej Gis
Andrzej Gis

Reputation: 14316

In your ManageTasks action you return AssignTask(model). This doesn't work, because the request context still remembers that the user actually called ManageTasks. That's why it returns the view for ManageTasks.

The right way to do it is like that:

return RedirectToAction("AssignTask", model); // remember to pass the model here

You can see that if you put this line in AssignTask:

HttpContext.Request.Path

If you access it from ManageTasks using return AssignTask(model), the value will be "/YourController/ManageTasks".

If you either call this action directly from browser or with RedirectToAction the value will be "/YourController/AssignTask".

Upvotes: 2

Matt Bodily
Matt Bodily

Reputation: 6413

you can't redirect that way. instead of return AssignTask you need

return RedirectToAction("AssignTask");

and pass an id or something there. you will need to recreate the model in your AssignTask method

Upvotes: 0

Related Questions