【问题标题】:Rendering Partial Views using ajax使用 ajax 渲染局部视图
【发布时间】:2011-11-17 20:39:45
【问题描述】:

我检查了this question,它解决了我最初的问题。但我不希望仅在用户单击链接时呈现部分视图,我希望在加载页面时呈现部分视图,并且可能在加载部分视图时显示进度指示器。

如何实现?

非常感谢您阅读本文。

【问题讨论】:

    标签: c# jquery asp.net-mvc ajax razor


    【解决方案1】:

    如果您想加载页面,然后通过 ajax 加载部分视图,您可以创建一个 ActionMethod,执行以下操作:

    public ActionResult Create()
    {
         var model = new MyModel();
    
         if (Request.IsAjaxRequest())
         {
              return PartialView( "_Partial", model.PartialModel );
         }
         else
         {
              return View( model );
         } 
    }
    

    然后在您的页面中执行以下操作:

    $(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);
              }
        });
    });
    

    【讨论】:

      【解决方案2】:

      控制器

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

      在默认页面上(使用 jquery ajax 操作)

      <div id='mod1'>Loading...</div>
      <script type="text/javascript">
                  $("#mod1").load("/ControllerName/GetModule?partialName=test1");         
      </script>
      

      【讨论】:

      • 需要放Partial View的文件格式吗?喜欢 .cshtml
      【解决方案3】:

      你可以通过写@Html.Partial(...)在初始页面渲染它。

      【讨论】:

      • 认为@Html.Parital不能在Ajax、jquery中使用。
      • @Shan:这是服务器端的事情;与此无关。
      • @SLaks,似乎他需要在显示主视图后显示部分视图(可能是为了避免长时间的初始处理)。据我所知,您建议的@Html.Partial() 与主视图一起在服务器上处理。所以它并没有解决男人的问题。我最初也被这个问题欺骗了。
      猜你喜欢
      • 1970-01-01
      • 2010-10-19
      • 2016-01-03
      • 1970-01-01
      • 2018-01-16
      • 1970-01-01
      • 2011-04-08
      • 2023-03-30
      相关资源
      最近更新 更多