简体   繁体   中英

How to show alert, popup or message if file is not created in MVC?

I have a action method:

public ActionResult Export(int? protocol, int? visitno)
{
    SetViewBagItems();
    if(protocl.hasValue)
    {
        // code create file
        if (!string.IsNullOrEmpty(csvData))
        {
            return File(new System.Text.UTF8Encoding().GetBytes(csvData), "text/csv", "Report.csv");
        }
        else
        {
            // need to show something in ui like, not able to create file, or any popup or any alert.... 
        }
    }
    return view();
}

So in the code as mentioned, I need to show something like an alert or message when able to create the file.

Now the behavior is:

  • if file gets created, it will get directly downloaded and wont reload the page.
  • if no file is created, then the entire page will refresh.

I need to show some message instead of that.

Same controller method is used for the page to load for the first time.

How can I achieve this?

Using $.ajax() to call that function in controller. Likes:

    $.ajax({
        url: "/controller/action",
        type: "GET",
        data: {protocol: protocol, visitno: visitno},
        success: function(e) {
             if(e != null)
             {
                  //Alert
             }
             else {
                  //Alert
             }
        }
   })

You can return a JSON result from your action method as:

return Json(new { 
                  success = true, 
                  status = "Failure" 
                }, JsonRequestBehavior.AllowGet);

The ajax method from where the action method is called, check for the return status and show the error or success message in the dialog box or through alert:

$.ajax({
     type: "POST",
     url: "/Controller/Action",
     data: { "ID": $('#id').val() },
     success: function (data) {
     if (data.status == "Failure")
      {
          $('#dialog-Add-Success').dialog({
          modal: true,
          opacity: 1,
          buttons: {
           Ok: function () {
                            $(this).dialog('close');
                           }
            },
         })
       }

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