1

I'm trying to create my own html helper. I need to add some javascript to the string I return.

public static string ListCheckbox(this HtmlHelper helper, string actionName, int value)
{
        return String.Format("<input type='checkbox' value='{1}' onclick='Action_{0}()'></input>", actionName, value);
}

How can I add this javascript, assuming that I want to keep this code in separate *.js file?

In *.cshtml file I can do it like that:

@Scripts.Render("~/Scripts/App/markSearched.js")

But this doesn't work in c# file. HtmlHelper helper variable doesn't have anything like "Scripts" or "Render". Can I use those function in c# class?

1 Answer 1

1

You can reuse output of System.Web.Optimizaton.Scripts.Render static method as following

using System.Web.Optimization;
 public static class CheckBoxHelper
 {
    public static MvcHtmlString ListCheckbox(this HtmlHelper helper, string actionName, int value,string jsPath)
    {
        var builder = new StringBuilder();
        builder.Append(Scripts.Render(jsPath).ToHtmlString());
        builder.AppendFormat("<input type='checkbox' value='{1}' onclick='Action_{0}()'></input>", actionName, value);
        return new MvcHtmlString(builder.ToString());
    }
  }

It's important to use MvcHtmlString as return type, or output will be html-encoded otherwise

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.