简体   繁体   中英

How do I detect if my page is the result of a postback

I have a combo box on an MVC3 application. When a new item is selected it does a post back as I want it to. All fine there. In the process I pop in a querystring and read it on page load. When the page refreshes it reads the query string and sets the other controls as needed.

However, I need to detect when the page reloads, that it is as a result of a postback, as opposed to the first time the page loads. This is because when the page loads initially, everything is messed up until someone picks something from the combobox.

However, a new user to the site wont know that and will just see a mess.

I understand that MVC3 apps don't have the same isPostback as ASP.Net has and for various reasons that I don't understand, I know it is somehow not considered "accaptable".

However, I am just interested in knowing if there is a 100% guaranteed reliable way to differentiate between a page first loading, and a postback in the same manner as was done in ASP.Net. If there is such a way, what is it and how can I implement it.

I have seen other post's that do this:

    public bool IsPostBack
    {
        get
        {
            return ViewBag.IsPostBack = (Request.HttpMethod == "POST");
        }
    }

but I read other places that this is always true. So therefore if this is always true it will be true on first load too and in so being, I cant tell reliably if it is a postback or not. I know of course it is a postback of some sort. But it is not if it is a first load.

Can anyone help me with an answer to this please. Also I am using the Razor view engine as opposed to standard aspx view engines.

In MVC, you typically have different actions for GET and POST:

[HttpGet] // Actions are GET by default, so you can omit this
public ActionResult YourAction(int id)
{
    // GET
}

[HttpPost]
public ActionResult YourAction(YourModel model)
{
    // POST
}

If you follow this pattern, there is no need to worry about a Page.IsPostBack -like property.

As you said, there's no notion of Postback in ASP.NET MVC. What you cold do is to test the HTTP verb that was used to perform the request to see if it is POST. This could be either after a form submission or an AJAX request:

public ActionResult Foo()
{
    if (string.Equals("post", Request.HttpMethod, StringComparison.OrdinalIgnoreCase)
    {
        // The POST verb was used to invoke the controller action
    }
    ...
}

You can decorate the action with the proper attributes

[HttpGet]
public ActionResult Foo() { 
    //Do pre-postback stuff here 
}

[HttpPost]
public ActionResult Foo() { 
    //Do postback stuff here 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM