EasyE
EasyE

Reputation: 580

Displaying an error message from my controller, and redirect back to my homepage

I am currently making a DB query request that is being sent from my view "Index.cshtml", however I am trying to give a user a message if they entered a selection that did not come back with with any result. Currently I have found an example that provide the user a JS box showing them a message when their query comes back empty. However, when they receive the message it redirects them to a blank page.

My goal is Have a user receive a message when their query request comes back empty. And just reload the webpage in order for them to retry their query. This is the following code that I have.

Code

        public ActionResult GetClientList(int? marketGroup, int? engagementOffice, int? engagementpartner, int? engagementStatus)
    {
        List<Engagement> QueryResult = PMService.GetRequestedEngagments(marketGroup, engagementOffice, engagementpartner, engagementStatus); 

        if(QueryResult.Count==0)
        {                
            return View("<script language='javascript' type='text/javascript'>alert('Your Search Came Back Empty Please Retry ');</script>");
        }


        var writetofile = PMService.BuildCsvString(QueryResult);
        var bytefile = Encoding.UTF8.GetBytes(writetofile);


        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=SqlExport.csv");
        Response.Charset = "";
        Response.ContentType = "application/text";
        Response.BinaryWrite(bytefile);
        Response.Flush();
        Response.End();

        return View();

    }

Currently my condition is catching if the list is being returned empty and giving a message, but after that it takes them to a blank page.

Upvotes: 0

Views: 70

Answers (3)

Gelootn
Gelootn

Reputation: 601

First use

return File(filedata, contentType);

to return a file from a memory stream or a file on the server disk

to check if the file will contain any data you could do an Ajax request first to check the nr of records that will be returned. If you get 0 just alert the user, if you get more the zero redirect the user to the Actionresult that returns the file.

Upvotes: 0

Alex C
Alex C

Reputation: 137

Response.End() is the reason why you get a blank page you probly want a redirection instead Response.Redirect("/")

Upvotes: 1

profesor79
profesor79

Reputation: 9473

The script is lacking a redirect statement. you could add:

 window.location.assign("http://www.w3schools.com");

in script tag, to direct browser to new page.

Upvotes: 1

Related Questions