tags:

views:

1825

answers:

2

I have actions in different controllers that need to check for a some condition before execution. If the condition is not met, I want the user be redirected to another page with instructions on what to do next (the instructions will include a link that the user must follow).

For example SendMessage() action is located in the Message controller:

public ActionResult SendMessage()
{
    // check if user has enough credit
    if (!hasEnoughCredit(currentUser))
    {
     // redirect to another page that says:

     // "You do not have enough credit. Please go to LinkToAddCreditAction
     // to add more credit."
    }

    // do the send message stuff here 
}

I want to have a single generic action called ShowRequirements() located in Requirements controller.

In SendMessage() action, I would like to set the message that I want to show to the user and then forward the user to ShowRequirements() action. I just don't want the message to appear in the URL of the ShowRequirements action.

Is there any way to communicate this data to ShowRequirements() action?

+1  A: 

You can put it in TempData["message"] which is passed to the new action being redirected to.

John Sheehan
This is probably the best solution, but it sounds like you might want to reconsider your business logic. Why do two disjoint actions need to occur together, connected via a redirect in order for some process to occur? Perhaps you need to abstract some code?
Andrew Bullock
Correct. You could just return the view (with ViewData/ViewModel) required to display the error without the redirect
John Sheehan
Andrew, I can not think of any other way to check for these condition and act accordingly. How do you go about doing the same scenario?
xraminx
Ok, then each view is responsible for showing the error message / instructions for that action? I gotta check for some flag in the view and show the message instead of normal results that would have been shown by that view?
xraminx
A: 

Okay, I think I was getting it wrong. As John and Andrew mentioned I simply have to pass the data via ViewData to a view.

So I made a RequirementsPage.aspx in the /views/Shared. Now in whichever action I am, I fill in the ViewData dictionary and pass it to the RequirementsPage.aspx like this:

public ActionResult SendMessage()
{
    // check if user has enough credit
    if (!hasEnoughCredit(currentUser))
    {
        // redirect to another page that says:
        ViewData["key1"] = "some message";
        ViewData["key2"] = "UrlToTheAction";
        return View("RequirementsPage");
    }

    // do the send message stuff here 
}
xraminx