Why ViewBag or TempData cannot shown on View when using AJAX?

1.3k views Asked by At

Before using Ajax, I used to return data with ViewBag or TempData properly. However, when using Ajax, none of the prior methods do not work even if trying to force with Javascript. Could you please clarify me where I made mistake?

Controller:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = null)] MyModel model)
{
    //... removed for brevity  
    TempData["message"] = "My tempdata message";
    ViewBag.message= "My viewbag message";
}

View:

/* Method I: I tried to show data as I used to before using Ajax. But, now it 
is not displayed as below (Normally I use one of them, not both of course) */
@if (TempData["message"] != null || ViewBag.message != null)
{
    //The code hits here but the message is not displayed
    <div class="text-danger">@TempData["message"]</div>
    <div class="text-danger">@ViewBag.message</div>
}
else
{
    <div class="noMessage"></div>
}


Method II:
<div class="text-danger" id="divSuccessMessage" style="display:none;">@ViewBag.message</div>    


<script type="text/javascript">
$(function () {

    $('form').submit(function (event) {
        event.preventDefault();            
        var formdata = new FormData($('#frmCreate').get(0));
            $.ajax({
                type: "POST",
                url: '@Url.Action("Create", "Issue")',
                data: formdata,
                processData: false,
                contentType: false,
                error: function (response) {
                    if ('@ViewBag.message' != "") {
                        $('#divSuccessMessage').show();
                        alert('test'): //The code hits here, but the message 
                        //is not displayed in divSuccessMessage with ViewBag or Tempdata. 
                        //On the other hand, if I use just a text in divSuccessMessage, it is displayed.
                    }
                }
            });
        }

});
0

There are 0 answers