ASP.NET MVC Finding out the caller to a method whe

2019-06-27 05:12发布

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?

3条回答
闹够了就滚
2楼-- · 2019-06-27 05:59

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...

查看更多
forever°为你锁心
3楼-- · 2019-06-27 06:01

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.

查看更多
做个烂人
4楼-- · 2019-06-27 06:06

Sounds to me like you are after:

Request.UrlReferrer

Let me know if you're not.

HTHs,
Charles

查看更多
登录 后发表回答