Search code examples
javascriptasp.net-mvcrazorknockout.jsquotes

Razor escaping single quotes in data attributes


I'm trying to get Razor to display a dropdown list with data_bind attibutes for knockout

so starting with

 @Html.DropDownListFor(model => model.Form.selectedItem, Model.empty, new
               {
                    @class = "multiselected" 

               })

I've tried multiple things to get the data added using this with a dictionary object

 { "data_bind" , MvcHtmlString.Create("options: optionSelected, optionsText: 'name', optionsValue: 'id', optionsCaption: 'Choose...'") }

This

 "data_bind" = MvcHtmlString.Create("options: optionSelected, optionsText: 'name', optionsValue: 'id', optionsCaption: 'Choose...'") 

 "data_bind" = Html.Raw("options: optionSelected, optionsText: 'name', optionsValue: 'id', optionsCaption: 'Choose...'") 

"data_bind" = Html.Raw(MvcHtmlString.Create("options: optionSelected, optionsText: 'name', optionsValue: 'id', optionsCaption: 'Choose...'"))

Whatever I try the single quotes get changed to '. What gives?

Edit

Turns out that knockout doesn't mind the quotes and can still bind. The other questions don't relate to knockout and data attributes. In list/input elements.


Solution

  • Even if the single quotes are escaped in the html, this won't affect the binding, which will see them correctly as single quotes.

    ko.applyBindings({
      options: [{ name: 'first one', id: '1' },
                { name: 'second one', id: '2' }, 
                { name: 'third one', id: '3' }]
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
    
    <select data-bind="options: options, optionsText: &#39;name&#39;, optionsValue: &#39;id&#39;, optionsCaption: &#39;Choose...&#39;">
    </select>

    https://jsfiddle.net/oxtupfx8/