简体   繁体   中英

How to detect postback in javascript?

I need to fill the text with current datetime only on a first page load using Javascript. I mean that I'm looking for analog to Page.IsPostBack property in ASP.NET, but in JS.

I've found solutions, where I was adviced to use server-side code to detect postback and pass a variable to client-side. But I'm using MVC, and there is no property such as Page.IsPostBack...

Please, help me find the answer

There's no such think on MVC. You've actions that can handle POSTs, GETs or both. You can filter what each action can handle using [HttpPost] and [HttpGet] attributes.

On MVC, the closest you can get to IsPostBack is something like this within your action:

public ActionResult Index() 
{
    if (Request.HttpMethod == "POST") 
    {
        // Do something
    }

    return View();
}

Therefore,

[HttpPost]
public ActionResult Create(CreateModel model) 
{
    if (Request.HttpMethod == "POST") // <-- always true
    {
        // Do something
    }

    return RedirectToAction("Index");
}    

ref: MVC3 Page - IsPostback like functionality

You can do something like this:

 <script>
    function myFunction() {
      // ...
    }

    @if (Request.HttpMethod == "POST")
    {
       @Html.Raw("myFunction();")
    }
</script>
[HttpPost]
public ActionResult MyAction()
{

   ViewBag.IsPostBack=true;

}

Then in your view

<script>
  var isPostBack=@ViewBag.IsPostBack;
</script>

You're missing here that you're working with MVC, there's no such "post back" concept. In your view, in the controller GET method, fill the value for the date. In the corresponding POST, you'll get this value or some other filled by the user. So, if it's a post, you'll never pass for the line of code filling the date for the first time.

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