HtmlHelpers for managing scripts for Razor Partial

2019-07-04 10:46发布

问题:

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");
}