简体   繁体   中英

Alert Success or Error message for jQuery POST method

I'm using the following jQuery to submit and save data:

var data = "Sample data";
$.post('@Url.Content("~/Student/SaveData")', { Data : data}
//I want to alert SUCCESS or ERROR here

This is my controller:

public ActionResult SaveData(string data)
{
  try
  {
      //Add logic to save data
      //pass SUCCESS indication.
  }
  catch(Exception ex)
  {
      //pass ERROR indication
  }
return View();
}

I want to alert success message if data saved successfully otherwise error message. How to handle it in jQuery section?

you are firstly using wrong helper instead of @Url.Content you need to use @Url.Action which generates url for you action:

and use $.ajax like this:

 var data = "Sample data";

$.ajax({
                url: '@Url.Action("SaveData","Student")',
                type: "get",
                data: { sample:data}
                success: function (res) {
                    alert("success");
                },
                error: function () {
                    alert("failure");

                }
            });

and your action would be like:

public ActionResult SaveData(string sample="")
{

return Content(sample);

}

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