25

I've checked this question and it solved my initial problems. But I don't want the partial view to be rendered only when the user clicks a link, I want to render partial views when the page is loaded and, possibly, show a progress indicator while the partial view is being loaded.

How to achieve that?

Thank you very much for reading this.

Community
  • 1
  • 1
programad
  • 1,291
  • 3
  • 19
  • 38

3 Answers3

70

If you want to load the page and then load the partial view via ajax you could create an ActionMethod that does something like:

public ActionResult Create()
{
     var model = new MyModel();

     if (Request.IsAjaxRequest())
     {
          return PartialView( "_Partial", model.PartialModel );
     }
     else
     {
          return View( model );
     } 
}

and then in your page do something like:

$(function(){

    $(document).ajaxStart(function () {
        //show a progress modal of your choosing
        showProgressModal('loading');
    });
    $(document).ajaxStop(function () {
        //hide it
        hideProgressModal();
    });

    $.ajax({
          url: '/controller/create',
          dataType: 'html',
          success: function(data) {
             $('#myPartialContainer').html(data);
          }
    });
});
ericb
  • 3,400
  • 1
  • 21
  • 21
13

Controller

public ActionResult GetModule(string partialName){
    return PartialView("~/Views/Shared/"+partialName);
}

on the Default Page (using jquery ajax operation)

<div id='mod1'>Loading...</div>
<script type="text/javascript">
            $("#mod1").load("/ControllerName/GetModule?partialName=test1");         
</script>
ebattulga
  • 10,774
  • 20
  • 78
  • 116
6

You can render it in the initial page by writing @Html.Partial(...).

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Think @Html.Parital can't be used in Ajax, jquery. – Shan Mar 01 '17 at 17:39
  • 1
    @Shan: It's a server-side thing; it has nothing to do with that. – SLaks Mar 01 '17 at 17:51
  • @SLaks, seems like he needs the partial views to display after the main view is displayed (probably to avoid long time initial processing). As far as I know @Html.Partial() that you propose is processed on server along with the main view. So it does not solve the mans problem. I was also tricked by the question initially. – cnom Aug 22 '17 at 14:58