开发者

ASP.NET MVC Finding out the caller to a method when !ModelState.IsValid

开发者 https://www.devze.com 2022-12-08 09:29 出处:网络
I haveaction 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 a

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 differe开发者_Python百科nt controllers may post to the method. Is there something in the ViewData that I can use to findout who called my Action Method?


Sounds to me like you are after:

Request.UrlReferrer

Let me know if you're not.

HTHs,
Charles


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消