ygongdev
ygongdev

Reputation: 284

MVC5 how to send string from controller to view?

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
    }
}

Upvotes: 0

Views: 81

Answers (1)

afnpires
afnpires

Reputation: 609

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
    }
  }
}

Upvotes: 1

Related Questions