display success message after deletion

1.7k Views Asked by At

I need to display a success message to user after the file has been deleted. dont know how to do it. please help.

    public ActionResult deleteGeneratedInvoice(string invoiceNumber)
    {
        try
        {
            string fileName = invoiceNumber.Trim() + ".pdf";
            string filePath = HostingEnvironment.MapPath("~/Content/reports/");
            string fullFilePath = filePath + fileName;
            System.IO.File.Delete(fullFilePath);

            //What shall i return here to display message?
            return
        }
        catch (Exception e)
        {
            InvoiceSearchTool.Models.udtExceptionTable exception = new udtExceptionTable();
            exception.MethodName = "deleteGeneratedInvoice";
            exception.Exception = e.ToString();
            exception.Date = DateTime.Now;
            DYNAMICS_EXTEntities db = new DYNAMICS_EXTEntities();
            db.AddToudtExceptionTables(exception);
            db.SaveChanges(); 
            //return View ("Error");
        }
    }
2

There are 2 best solutions below

3
On BEST ANSWER

//What shall i return here to display message?

ViewBag.SuccessMessage = "File was successfully deleted";
return View();

In your deleteGeneratedInvoice view, write this somewhere that makes sense:

<p>@(ViewBag.SuccessMessage ?? "")</p>
0
On

Well if you're deleting data in your app using this action, you should have it posted to the server in a form and specify a restriction on your action that it only responds to HttpPost, otherwise as soon as something tries to crawl your app you're going to be in for a rude awakening :-P

That being said, you have three choices for the returned information. You can return a new page (which is kind of silly if it's a blank page except for the "File deleted successfully" message).

Or you can setup your form to postback using Ajax by defining your form with yAjax.BeginForm() insead of Html.BeginForm() which gives you the two other options. Either return a Partial View from your delete action and have the partial view shows in a dynamically added DIV when the response completes (the most flexible in my eyes), or you can return a simple return code from your Delete action and then depending on that return code show different messages on your page. The Javascript methods that would handle these responses can be defined using the AjaxOptions parameter of the BeginForm() method. They are the javascript methods specified using the OnSuccess, OnError and OnComplete properties. Note they are not required but for the best user experience you should make sure to at least specify methods for the Success and Error ones.