Richard   Housham
Richard Housham

Reputation: 1680

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.

Upvotes: 1

Views: 981

Answers (1)

Michael Best
Michael Best

Reputation: 16688

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/

Upvotes: 3

Related Questions