Accessing div in view from controller

1.2k views Asked by At

In my layout page I've got this html:

 <div id="ajax-loading" class="global-loading-image" runat="server">
        <img src="/content/travelbill/img/small-loading-image.gif"/>
 </div>

Which is a loading-symbol. I want it to show when my code is doing its business. I've read on other threads here on Stackoverflow that if you use runat="server", you are supposed to be able to access the div in the controller. Like so:

   ajax-loading.Visible = true;
        EditTravelBillViewModel model = this.travelBillService.GetTravelBill(travelBillId);
        model.StageOfProcess = (int)TravelBillStageOfProcessEnum.APPROVED;
        this.travelBillService.Update(model, true);
        ajax-loading.Visible = false;
        return RedirectToAction("GetTravelBillsPerCompany");

But I get the error that the loading and the ajax do not exist in the current context. What am I doing wrong?

1

There are 1 answers

0
Remo H. Jansen On BEST ANSWER

That was in the old ASP.NET pages. In ASP MVC you don't have a ViewState, isPostBack or runat="server" you can pass variables from the controller to the view using ViewBag and ViewData like:

Controller:

ViewBag.Name = "My Name";
ViewData["Name"]  = "My Name";

View:

@ViewBag.Name
@ViewData["Name"]

I don't think you need to do that. You can have a action that do the task that you need to get done and with JavaScript request that action via AJAX. You can then with JavaScript show and hide the loading as you wish:

function LoadAjax(containerId, url, params){
  //Set loading in container
  $(containerId).html('<img src="loading.gif" alt="loading"/>');
  //Do the request
  $.ajax({
    type: 'POST',
    dataType: "html",
    url: url,
    data: params,
    success: function(data){
     // show response inside container (removes loading)
     $(containerId).html(data);
    },
    error: function( jqXHR, textStatus, errorThrown){
      // show error inside container (removes loading)
      $(containerId).html(textStatus);
    }
  });
}

While the page is loading it will display the loading image. You will need Jquery to use my code. Hope it helps.