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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With