デビッド、
私はまさにこのシナリオのための私のコードの静的htmlhelpersのカップルを使用します。 context.itemsコレクションが要求ごとに生成されるという原則に基づいて動作します。したがって、item.content.itemsコレクションにアイテムが存在する場合、それは2回追加されません。とにかく、wisdOOOmのスコットランド語の十分な、 'yillはCOADEをwaantinことJIST' ...私たちのスクリプトの
:私たちのかわいいCSSの
public static MvcHtmlString Script(this HtmlHelper html, string path)
{
var filePath = VirtualPathUtility.ToAbsolute(path);
HttpContextBase context = html.ViewContext.HttpContext;
// don't add the file if it's already there
if (context.Items.Contains(filePath))
return MvcHtmlString.Create("");
// add the beast...
context.Items.Add(filePath, filePath);
return MvcHtmlString.Create(
string.Format("<script type=\"text/javascript\" src=\"{0}\"></script>", filePath));
}
:
// standard method - renders as defined in as(cp)x file
public static MvcHtmlString Css(this HtmlHelper html, string path)
{
return html.Css(path, false);
}
// override - to allow javascript to put css in head
public static MvcHtmlString Css(this HtmlHelper html,
string path,
bool renderAsAjax)
{
var filePath = VirtualPathUtility.ToAbsolute(path);
HttpContextBase context = html.ViewContext.HttpContext;
// don't add the file if it's already there
if (context.Items.Contains(filePath))
return null;
// otherwise, add it to the context and put on page
// this of course only works for items going in via the current
// request and by this method
context.Items.Add(filePath, filePath);
// js and css function strings
const string jsHead = "<script type='text/javascript'>";
const string jsFoot = "</script>";
const string jsFunctionStt = "$(function(){";
const string jsFunctionEnd = "});";
string linkText = string.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}\"></link>", filePath);
string jsBody = string.Format("$('head').prepend('{0}');", linkText);
var sb = new StringBuilder();
if (renderAsAjax)
{
// join it all up now
sb.Append(jsHead);
sb.AppendFormat("\r\n\t");
sb.Append(jsFunctionStt);
sb.AppendFormat("\r\n\t\t");
sb.Append(jsBody);
sb.AppendFormat("\r\n\t");
sb.Append(jsFunctionEnd);
sb.AppendFormat("\r\n");
sb.Append(jsFoot);
}
else
{
sb.Append(linkText);
}
return MvcHtmlString.Create(sb.ToString());
}
使用量のどちらの場合:
<%=Html.Css("~/Content/Site.Css")%>
<%=Html.Script("~/Scripts/default.js")%>
楽しみを持っている...
[編集] - コメント行に特定のATTNを支払う:
// this of course only works for items going in via the current
// request and by this method
私は時間に一度、このことについて考えたが、私にとっての問題は、私が使用していたパーシャルのmiriadがマスターを汚染しているだろうということでしたファイルを使用した実際のコードが利用されたかどうかにかかわらず。私が推測するコースのための馬。あなたのアプローチは、代替cssとjs thoを持つパーシャルの膨大な拡散がないサイトではうまく機能します。 –
"Polluted?"あなたのweb.configの12行余分な行があなたを殺すことはありません。マスターの12行のコードが「巨大すぎる」場合は、複数のファイルを1つに結合します。動的である必要がある場合を除き、同じ部分が2つの異なるjquery/cssファイルを使用する可能性があることを意味します。 – jfar
jfar - 私たちは 'ANY他の解決法'に同意しないことに同意します - うん、:)あなたが参照する行の '数'は、12または24などであってもなくてもよい。さらに、マスターファイルには、常にすべての作業を継続するための継続的な「再訪」があります。これは私の場合(必ずしも上記のものではない)の冗長性などの可能性を開きます。「汚染」は確かに私の選択の任期です。猫や肌は実際には肉の種を作ります。[編集] - そして、おそらくダイナミックな性質が考慮されるかもしれません。とにかく、私はあなたに濡れた/風の強いスコットランドから良い夜を告げるでしょう。 –