Rendering Partial Views using ajax

2019-01-06 11:02发布

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.

3条回答
啃猪蹄的小仙女
2楼-- · 2019-01-06 11:12

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

查看更多
时光不老,我们不散
3楼-- · 2019-01-06 11:14

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);
          }
    });
});
查看更多
劫难
4楼-- · 2019-01-06 11:24

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>
查看更多
登录 后发表回答