Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HtmlHelpers for managing scripts for Razor Partial Views

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.

like image 775
s.k.paul Avatar asked Dec 03 '25 11:12

s.k.paul


1 Answers

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");
}
like image 192
Russ Cam Avatar answered Dec 05 '25 13:12

Russ Cam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!