1

Say I want to write an HTML helper to draw a chart. This helper would need to emit specific JS script code into the body of the page it was called from.

Is this recommended ?

If not how would i workaround that ?

Can i tell the helper to emit the code into a specific section defined in the main layout ?

1 Answer 1

1

This should do it:

public static class HtmlHelperExtensions
{
    public static MvcHtmlString HelloWorld(this HtmlHelper helper)
    {
        return new MvcHtmlString("alert('Hello World');");
    }
}

In Your Razor View:

<script type="text/javascript">

    @Html.HelloWorld();

</script>

You probably should not be doing this.

I would consider JS front end content that forms part of your view. Your view should simply display your view model.

I would be interested in knowing why you feel you need to be able to deliver JS in this way?

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

2 Comments

my need is to create a JSplot HtmlHelpr. drawing graphs with JSPlot require alot of js code to be emitted, can you think of any other way ?
sounds like a good enough reason, the above code should work then. give it a try.

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.