2012-09-06 37 views
9

我想弄清楚是否有可能追加到一個部分。這裏是我的結構:ASP.NET MVC 3:追加到部分

_Layout.cshtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> 
<head> 
<link href="@Url.Content("~/Content/style.css")" rel="stylesheet" type="text/css" /> 
@RenderSection("Css", false) 
<script type="text/javascript" src="@Url.Content("~/Content/scripts/head.load.min.js")"></script> 
</head> 
<body class="bg_g"> 
    @RenderBody() 
    <script type="text/javascript"> 
     @RenderSection("Javascript", false) 
    </script> 
</body> 
</html> 

Logon.cshtml

@{ 
    Layout = "~/Views/Shared/_DMZ.cshtml"; 
    ViewBag.Title = "Logon"; 
} 

@section Javascript += { 
    // JAVASCRIPT CODE; 
} 

<div> 
    Stuff 
    @{ Html.RenderAction("Register", "Account"); } 
    @{ Html.RenderAction("Register2", "Account"); } 
</div> 

Register.cshtml

@{ 
    Layout = null; 
} 

@section Javascript += { 
    // More javascript code 
} 

<div> 
    Register stuff 
</div> 

Register2.cshtml

@{ 
    Layout = null; 
} 

@section Javascript += { 
    // Even More javascript code 
} 

<div> 
    Register stuff part 2 
</div> 

希望能夠解釋我真正想做的事情。我也想用我的CSS部分做同樣的事情。它甚至會更好,如果我也能得到它呈現的Javascript這樣的:

head.js(
    "@Url.Content("~/Content/scripts/jquery-1.6.2.min.js")", 
    "@Url.Content("~/Content/scripts/jquery.tools.min.js")", 
    "@Url.Content("~/Content/lib/jquery-validation/jquery.validate.js")", 
// Loop through all javascript files included from the sub views and add them just like above 
function() { 
    loginTabs.init(); 
    // Loop through all javascript functions that have been added to the InitFunctions section? 
} 
) 

也許部分是不是正確的解決這個問題,但我知道,必須有有所建樹的方式喜歡這個。有任何想法嗎?

回答

0

遲進入的一點 - 但希望還是有用的人在那裏:

我不知道是否有實現它一個本地方法,但我一直在使用了一段時間,這是真正有用的:

public static IHtmlString Resource(this HtmlHelper HtmlHelper, Func<object, HelperResult> Template, string Type) 
{ 
    if(HtmlHelper.ViewContext.HttpContext.Items[Type] != null) ((List<Func<object, HelperResult>>)HtmlHelper.ViewContext.HttpContext.Items[Type]).Add(Template); 
    else HtmlHelper.ViewContext.HttpContext.Items[Type] = new List<Func<object, HelperResult>> { Template }; 

    return new HtmlString(String.Empty); 
} 

public static IHtmlString RenderResources(this HtmlHelper HtmlHelper, string Type) 
{ 
    if(HtmlHelper.ViewContext.HttpContext.Items[Type] == null) return new HtmlString(String.Empty); 

    var Resources = (List<Func<object, HelperResult>>)HtmlHelper.ViewContext.HttpContext.Items[Type]; 

    foreach(var Resource in Resources.Where(Resource => Resource != null)) 
    { 
     HtmlHelper.ViewContext.Writer.Write(Resource(null)); 
    } 

    return new HtmlString(String.Empty); 
} 

用法是:

//This is how you save it 
@Html.Resource(@<style>.test{color: #4e4e4e}</style>, "css") 

//This is how you read it 
@Html.RenderResources("css")