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?

3
  • 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? Commented Sep 10, 2012 at 23:37
  • 1
    because it's not generic. It would build the script based on the generated id from the extension. Commented Sep 11, 2012 at 0:40
  • This is one way: stackoverflow.com/a/5433722/453277 Commented Sep 11, 2012 at 1:10

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.