Grizzly
Grizzly

Reputation: 5953

Response.Write not working properly

In my Controller I have a conditional statement:

if (oLevel.PostPreID == 2)
            {
                if (db.OL.Any(x => DbFunctions.TruncateTime(x.Date) == DbFunctions.TruncateTime(oLevel.FlightDate) && x.PostPreID == oLevel.PostPreID && x.AID == oLevel.AID && x.deleted == false))
                {
                    Response.Write(@"<script language='javascript'>alert('There is already a PostPreID for this AID for this Date!');</script>");
                    return RedirectToAction("Index", new { id = oLevel.AID }); ;
                }                     
            }

now the conditional statement is working perfectly. The problem is the Response.Write alert.. it does not appear when this condition fires. Any reason as to why?

Any help is appreciated.

Upvotes: 0

Views: 1374

Answers (2)

Joel Coehoorn
Joel Coehoorn

Reputation: 416131

Because you call RedirectToAction() immediately afterwards. RedirectToAction() sends an HTTP 302 redirect response to the browser, causing to the browser to ignore anything in the body (such as your script) and instead redirect to the new url.

You could solve this by adding a View that looks for an additional argument telling it to render your alert (possibly as a lightbox, because browsers do weird things with alert() these days). But that doesn't seem right, either, because then anyone could view the alert just by visiting the url. Probably you want to do something more in your controller or session.

Upvotes: 4

HaukurHaf
HaukurHaf

Reputation: 13816

This is not the correct way to go about this. The reason the alert is not working is that immediately after you write it out to the response, you are redirecting to a different view, so the browser never renders the script tag you are outputting.

Instead of doing this, have the Index view rendered by the Index action conditionally output the script, based on a query-string parameter.

Pseudo-code:

 return RedirectToAction("Index", new { id = oLevel.AID, alreadyExists = true });

Then in the Index action/view, check if alreadyExists equals true and if so, have that view output the script tag and the alert message.

Upvotes: 4

Related Questions