HtmlHelpers for managing scripts for Razor Partial Views

我怕爱的太早我们不能终老 提交于 2019-12-10 19:03:24

问题


I'm trying to use Forloop HtmlHelpers for managing scripts for Razor Partial Views in my ASP.Net MVC 4 project.

 <div class="row-fluid">
  //some markups here
 </div>

 @{
  // begin a context for the scripts
   Html.BeginScriptContext();

   Html.AddScriptBlock(@"$(function() { alert('hello from the page'); } });");
   Html.AddScriptFile("~/Scripts/jquery-ui-1.8.11.js");

   // end the script context
   Html.EndScriptContext();
   }

But, it's throwing the following error during compile -

'System.Web.Mvc.HtmlHelper' does not contain a definition for 'BeginScriptContext' and no extension method 'BeginScriptContext' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)

I've installed this package via package manager console. How to overcome this issue?

Thank you.


回答1:


You need to add the Forloop.HtmlHelpers namespace

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="BaseTemplate.Web.Extensions.BaseTemplateWebViewPage">
      <namespaces>
        <! -- Add the following namespace to the others -->
        <add namespace="Forloop.HtmlHelpers" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

to the Web.config within the Views folder in your application.

A future update of the nuget package will add this for you. In the meantime, I have updated the wiki page with this information :)

EDIT : This is now performed as part of the nuget package installation.

Also, I would recommend using the following syntax as it's a little more terse

@using (Html.BeginScriptContext())
{
    Html.AddScriptBlock(
       @<script type="text/javascript">
           $(function() { alert('hello from the page'); } });
       </script>);
    Html.AddScriptFile("~/Scripts/jquery-ui-1.8.11.js");
}


来源:https://stackoverflow.com/questions/19685045/htmlhelpers-for-managing-scripts-for-razor-partial-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!