Search code examples
javascriptc#asp.netasp.net-mvcviewbag

ViewBag is not received in view after post action


When I executed method it return me an Error message who I want to display in bootstrap modal. So I put Message in ViewBag like this:

    [HttpPost]
    public ActionResult EnviarIncrementos(CapturaViewModel model)
    {
var res = service.GetService(fechaMovimiento);
 ViewBag.Message = res.Error;
 return RedirectToAction("Index");
    }

So when page redirect to Index I want to get ViewBag and show it into modal like this:

<div class="modal" id="myModal" tabindex="-1" role="dialog" data-keyboard="false" data-backdrop="static" style="overflow: hidden">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">Agregar nuevo archivo</h4>
      </div>
      <div class="modal-body col-md-12" id="modal-body">
        <div class="row">
          <div class="col-md-12">
            Resultados
            <br />
            <div class="" style="height: 150px; overflow: auto; margin-bottom:10px;">
              <pre id="resultado">@ViewBag.Message</pre>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-md-6">
            <button type="reset" id="limpiar" class="btn btn-default">Limpiar</button>
          </div>
          <div class="col-md-6 text-right">
            <button type="button" class="btn btn-default" data-dismiss="modal" onClick="window.location.reload();">Salir</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

JS:

 <script>
        $(document).ready(function () {
            if('@ViewBag.Message' != "") {
       $("#myModal").modal();
     }
});
    </script>

But modal don't show up and message is not there. What am I doing wrong?

Note: when page load in chrome debug JS change to this:

       $(document).ready(function () {
            if('' != "") {
       $("#myModal").modal();
     }
});

So @ViewBag is not received. Why it occurs?


Solution

  • I think you cannot use ViewBag when redirecting to another view, you can use TempData or Session for this. I think this reference will be helpful

    ViewBag, ViewData and TempData