Search code examples
jqueryajaxasp.net-mvcviewbag

Calling Viewbag Data from controller to view


Controller:-

[HttpPost]
        public ActionResult EmailScheduler()
        {
            long lCustDesignID = 1;
                int countProduct = gateWay.TotalCountOfCustomers(lCustDesignID);
                ViewBag.ItemCount = countProduct;

            return Json(JsonRequestBehavior.AllowGet);
        }

View:-

<h4>Number Of Records - <span>@ViewBag.ItemCount</span> </h4>

This controller is called on button click.

From Controller how to get value to View in viewbag.

.


Solution

  • If EmailScheduler is ajax call then you cannot use ViewBag like you have tried.

    You need to modify your code like below.

    Controller

    [HttpPost]
    public ActionResult EmailScheduler()
    {
       long lCustDesignID = 1;
       int countProduct = gateWay.TotalCountOfCustomers(lCustDesignID);                    
       return Json(countProduct,JsonRequestBehavior.AllowGet);
    }
    

    Html

    <h4>Number Of Records - <span id="spnCount"></span> </h4>
    

    Ajax

    $.ajax({
       //....
       success: function(data){
          $('#spnCount').text(data);
       }
    })