3

I'm trying to create an HTML helper extension that generates some javascript in addition to an HTML tag:

<select id="foo" name="foo"></select>

<script type="text/javascript">
    // script to populate select with data via $.getJSON
</script>

In the default MVC 4 template, they bundle the jquery scripts and put them at the end of the HTML document and have a scripts section:

@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)

Is there any way in an HTML helper extension to tell the script to get added to the end of the document, or do I just need to modify the Layout so that jQuery is at the top of the document?

Dismissile
  • 32,564
  • 38
  • 174
  • 263
  • 1
    If it's used multiple times, why wouldn't you just make a script file, create a bundle for it, link it after the jquery bundle, then put your generic code in $(document).ready? – mnsr Sep 10 '12 at 23:37
  • 1
    because it's not generic. It would build the script based on the generated id from the extension. – Dismissile Sep 11 '12 at 00:40
  • This is one way: http://stackoverflow.com/a/5433722/453277 – Tim M. Sep 11 '12 at 01:10

1 Answers1

2

Assuming you're using a ViewModel for your view, one way to achieve what you're after would be to separate the two things.

So in your View, you'd have something like this:

@Html.DropDownListFor(model => model.Foo, Model.FooList)
@section scripts { @Helpers.MyLittleJsCode(Model.Foo) }

The block @section scripts {} will render stuff where ever you placed the section in your layout (by default it's after the jquery bundle).

Create a folder called "App_Code" and inside that, create a razor file called "Helpers". Paste the following inside:

@using System.Web.Mvc;
@helper MyLittleJsCode(string jsString) {
<script type="text/javascript">
    alert("@jsString");
</script>
}

This will create a dropdownlist that you need, and create a script block at the end and pass Model.Foo into it. I hope this was what you were after.

mnsr
  • 12,337
  • 4
  • 53
  • 79