2013-04-10 139 views
1

我正在學習ASP.NET MVC,並試圖讓我的頭部部分視圖。我正在嘗試一個非常簡單的事情,這裏是我的源代碼。部分視圖覆蓋主視圖

_Layout.cshtml

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8" /> 
    <meta name="viewport" content="width=device-width" /> 
    <title>@ViewBag.Title</title> 
    @Styles.Render("~/Content/css") 
    @Scripts.Render("~/bundles/modernizr") 
</head> 
<body> 
    @RenderBody() 

    @Scripts.Render("~/bundles/jquery") 
    @RenderSection("scripts", required: false) 
</body> 
</html> 

_ViewStart.cshtml

@{ 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
} 

HomeController.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 

namespace MvcApplication4.Controllers 
{ 
     public class HomeController : Controller 
     { 
       public ActionResult Index() 
       { 
         return View(); 
       } 

       public PartialViewResult UpdateDate() 
       { 
        return PartialView("Partial1"); 
       } 
     } 
} 

Index.cshtml

@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 
@DateTime.Now 
<br /> 
@{Html.RenderPartial("Partial1");} 
<br /> 
@Html.ActionLink("Render Partial", "UpdateDate") 

Partial1.cshtml

@DateTime.Now 

現在,當我點擊渲染部分鏈接UpdateDate動作方法被調用,但渲染局部視圖覆蓋的主要內容,我只看到局部視圖的內容。爲什麼我會丟失Index.cshtml的內容?

我需要做什麼才能顯示Index.cshtml的內容,並且僅顯示部分視圖內容?

回答

4

爲什麼我會丟失Index.cshtml的內容?

因爲您需要使用AJAX調用。現在你所擁有的是一個常規鏈接,它被呈現爲標準的<a>元素,正如你知道當你點擊任何網頁中的錨點時,瀏覽器只是重定向到href屬性指向的url。這就是所謂的超級鏈接,萬維網上充滿了它們。

所以,你可以通過給你的鏈接一個唯一的ID可以在自定義腳本後來被用來啓動:

@Html.ActionLink("Render Partial", "UpdateDate", null, null, new { id = "myLink" }) 

也把你分在一個容器:

<div id="myPartial"> 
    @{Html.RenderPartial("Partial1");} 
</div> 

終於訂閱到此鏈接的.click()事件併發送AJAX呼叫而不是常規重定向:

@section scripts { 
    <script type="text/javascript"> 
     $('#myLink').click(function() { 
      $.ajax({ 
       url: this.href, 
       type: 'GET', 
       cache: false, 
       success: function(result) { 
        $('#myPartial').html(result); 
       } 
      }); 
      return false; 
     }); 
    </script> 
} 

在這個例子中,我已經覆蓋了視圖中的自定義腳本部分,以編寫JavaScript。但當然這只是用於演示目的。好的做法決定了javascript代碼應該放在單獨的javascript文件中,而不是與標記混合在一起。因此,在現實世界的應用中,這應該被重構爲:

@section scripts { 
    @Scripts.Render("~/bundles/mybundle") 
} 

哪裏~/bundles/mybundle顯然,你會在~/App_Start/BundleConfig.cs文件指向你的外部JS自定義一個包。


另外,您可以使用一個Ajax.ActionLink而不是常規的Html.ActionLink

@Ajax.ActionLink("Render Partial", "UpdateDate", new AjaxOptions { UpdateTargetId = "myPartial" }) 

但對於這個工作,你需要包括jquery.unobtrusive-ajax.js腳本到您的網頁。由於您使用的是ASP.NET MVC 4和捆綁包,您可以在您的_Layout中包含~/bundles/jqueryval捆綁包:

@Scripts.Render("~/bundles/jquery") 
@Scripts.Render("~/bundles/jqueryval") 
@RenderSection("scripts", required: false) 
+0

感謝您的解釋。 – user2265934 2013-04-10 12:49:51