0

I have a controller that tries to download a file, if the file fails I want to send a string to the view to display the error. I'm trying to accomplish this using TempData, I'm having some trouble. The error shows when file is not downloadable, but when the file successfully downloads, the error message doesn't disappear. What might I be doing wrong?

Controller

        if (can_download)
        {

            Response.ContentType = contentType;
            Response.AppendHeader("Content-Disposition", string.Format("attachment; filename={0}", filename));
            Response.TransmitFile(path);
            Response.End();
        }
        else
        {
            TempData["AlertMessage"] = "File failed to save";

        }
        return RedirectToAction("Index", page);

View

@{
    var message = TempData["AlertMessage"];
}

<p class="error-msg">@message</p>

@section scripts {
    var message = '@message';
    if (message){
         $('.error-msg').css('opacity', 100); // show message
    }else{
         $('.error-msg').css('opacity', 0); // hide message
    }
}

1 Answer 1

1

You have to clear the TempData if the file is generated successful.

There's a change that, in a previous error, the TempData is not consumed.

if (can_download)
    {

        Response.ContentType = contentType;
        Response.AppendHeader("Content-Disposition", string.Format("attachment; filename={0}", filename));
        Response.TransmitFile(path);
        Response.End();

        TempData["AlertMessage"] = string.Empty;

    }
    else
    {
        TempData["AlertMessage"] = "File failed to save";

    }
    return RedirectToAction("Index", page);

View

@{
    var message = TempData["AlertMessage"] as string;
}

@if (!string.IsNullOrEmpty(message)) {
 <p class="error-msg">@message</p>

@section scripts {
    var message = '@message';
    if (message){
     $('.error-msg').css('opacity', 100); // show message
    }else{
     $('.error-msg').css('opacity', 0); // hide message
    }
  }
}
Sign up to request clarification or add additional context in comments.

7 Comments

Oh I see. Btw in (!string.IsNullOrEmpty(message) it says message is an object, not a string. How can I fix that?
forgot the cast of TempData[... ] to string, sorry. Edited it.
Same problem still occurs :( Once I click on a undownloadable file, I get the error. Then if I click on a downloadable file, the error is still there :(
Then my bet is that the view is not being refreshed on a file download. Place a DateTime.Now in the view and see if the value changes on a file download.
Then I would make the TempData message disapear after 5 seconds or so with javascript.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.