Search code examples
javascriptasp.net-mvcrazorhtml-helper

html dropdownlist helper in javascript


I'd to set a local javascript variable to the output of an html helper. See the following snippet for an example:

<script type="text/javascript">
     $(function () {
              var dtypes = '@Html.DropDownList("TypeId",new SelectList(@ViewBag.MyTypes,"Value","Text"))';
      });
      alert(dtypes);
</script>

This doesn't give me an alert. Am I doing something wrong? Thanks for any help.


Solution

  • You should encode your html to be valid JavaScript string:

    <script type="text/javascript">
     $(function () {
              var dtypes = '@Ajax.JavaScriptStringEncode(Html.DropDownList("TypeId",new SelectList(@ViewBag.MyTypes,"Value","Text")))';
      });
      alert(dtypes);
    </script>