2016-11-04 51 views
0

在我的MVC應用程序中,我不希望佈局頁面在每次選擇視圖時重新加載。如果可以使用ajax加載視圖以保持內容快捷並允許我在移動時保留某些被刪除的界面狀態,那將是非常好的。如何使用AJAX從佈局請求視圖?

我最初的做法是向_Layout.cshtml添加一些ajax,然後當他請求查看時,將該請求傳遞給將要抓取該頁面的控制器方法。我最終做的是再次返回整個視圖。

這是我到目前爲止的代碼,我是在正確的軌道上,還是完全錯誤?

佈局阿賈克斯腳本

<script> 
    $(function() { 

     var content = document.getElementById('content'); 

     //When a user selects a link, pass the data attribute and 
     //use it to construct the url 
     $('#sidebar a').on("click", function() { 

      var page = $(this).data('page'); 
      console.log("Data Attrib : " + page); 

      $.ajax({ 
       type: 'GET', 

       url: '@Url.Content("~/Home/")' + page,      
       success: function (data) { 
        $('#content').html(data); 
        console.log("Success"); 
       }, 
       error: function (xhr, ajaxOptions, thrownError) { 
        console.log("Error: " + thrownError); 
       } 
      }) 
     }) 
    }); 
</script> 

正如我所說,這類作品,但因爲它返回整個頁到包括佈局內容方面它並不是完美的,理想的我只想核心查看數據。

+0

把這個在您不希望包括佈局視圖的頂部:'@ { Layout = null;}' – Ric

+1

另一種選擇是使用部分視圖並檢索那些 - 他們不mak e使用佈局模板並設計爲插入到另一個頁面內。 – ADyson

回答

1

您可以創建一個單頁面應用程序,它具有1個佈局,並且在家庭控制器和索引操作方法中創建菜單或用戶設置或其他東西 現在您可以使用Ajax調用帶有數據內容的html加載其他操作有佈局文件,並追加在容器 當用戶單擊另一個菜單幹淨的舊內容和添加新的,或者可以創建標籤條或窗口

0

Layout.cshtml

<script> 
$(function() { 

    //When a user selects a link, pass the data attribute and 
    //use it to construct the url 
    $('#sidebar a').on("click", function() { 

     var page = $(this).data('page'); 

     $.ajax({ 
      type: 'POST', 
      url: '/Home/Pages', 
      data: { pageValue: page }, 
      success: function (data) { 
       $('#content').html(data); 
       console.log("Success"); 
      }, 
      error: function (xhr, ajaxOptions, thrownError) { 
       console.log("Error: " + thrownError); 
      } 
     }) 
    }) 
}); 

控制器

public class HomeController : Controller 
{ 
    [HttpPost] 
    public string Pages(string pageValue) 
    { 
     string result = //Whatever 

     return result; 
    } 
} 
0

控制器

public ActionResult SomeAction(String someparams) 
    { 
     //Make the model 
     SomeModel someModel = new SomeModel(); 
     someModel.someparams = someparams; 
     return PartialView("SomePartialView", someModel); 
    } 

在查看

$.ajax({ 
       url: "/Home/SomeAction", 
       type: "POST", 
       dataType : "html", 
       data: json, 
       contentType: 'application/json; charset=utf-8', 
       success: function(data){ 

        $('#SomeDivID').html(data); 
       } 
    });