views:

112

answers:

3

I have action method on my "CartController" an AddtoCart that returns an ActionResult. The problem I'm having is that I post from antoher controller to the AddtoCart the Id of the product i want to add, then move on. I have no problem with the validation; however, it's when I want to redirect to the View that called the Action when the !ModelState.IsValid, that I don't know who called me (or where to find it).

It is possible that several different controllers may post to the method. Is there something in the ViewData that I can use to findout who called my Action Method?

A: 

I don't think that controllers are making the post. Controllers are accepting the requests ( posts) and do some work, retrieve data and then choose which view to render back to the browser.

So, your action methods are normally called from web browser (link on the page, javascript). That is why I suggest you to pass additional parameter to the Action methods and then based on that value choose appropriate view to render back.

public ActionResult AddToCart(int productID, string caller)
    {
        //add to cart logic

        switch (caller)
        {
            case "this":
                {
                    //get data for this view
                    return View("this");
                }
            case "that":
                {
                    //get data for that view
                    return View("that");
                }
            default:
                {
                    //get data for default view
                    return View("default");
                }
        }
    }

Hope that I understood well what is the nature of your problem...

Misha N.
A: 

I think you're after something like this:

[...] if you don't mind having your code tied to the specific view engine you're using, you can look at the ViewContext.View property and cast it to WebFormView

var viewPath = ((WebFormView)ViewContext.View).ViewPath;

from a related question about getting the view name from inside a controller method.

Dylan Beattie
A: 

Sounds to me like you are after:

Request.UrlReferrer

Let me know if you're not.

HTHs,
Charles

Charlino
I tried, that but it give the actual url, and I can't just return View(Request.UrlReferrer) if there is an error in the ModelState.Thanks though!
Mike
Could you put your the ModelState into TempData and then do a redirect to the Request.UrlReferrer? The actions/views that you post from and subsequently have to redirect to will surely need to get data/stuff for their own views...? No?
Charlino