I have a listbox that I am populating using a foreach. (Long explanation of why I need to do this.)
I need to escape the string because fname and lname can contain special characters, like ‘ or “.
foreach (var cust in item.Customers)
{
var custString = string.Format("{0}%#%{1}%#%{2}", cust.CustID, cust.LName, cust.FName);
<option value="@custString">@cust.DisplayName</option>
}
Is there any way to do a javascript escape of custString right after setting the value? Or is there there a preferred C# way of escaping that will work well with javascript’s unescape, which I am using to unescape these chars.
That’s what the
AttributeEncodehelper does:But hey, what are you doing? foreach loop to generate a dropdown list????
Try the
Html.DropDownListForhelper and stop the bleeding inside your view before its too late. This helper does what its name suggests. And takes care of encoding and escaping and whatever.So simply define a view model:
then go ahead and have your controller action populate and pass this view model to the view:
and inside the view, use the DropDownListFor helper when you need to generate a dropdown list: