Reputation: 103
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.
Upvotes: 0
Views: 2706
Reputation: 1038720
That's what the AttributeEncode
helper does:
<option value="@Html.AttributeEncode(custString)">@cust.DisplayName</option>
But hey, what are you doing? foreach loop to generate a dropdown list????
Try the Html.DropDownListFor
helper 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:
public class MyViewModel
{
public string CustomerId { get; set; }
public IEnumerable<SelectListItem> Customers { get; set; }
}
then go ahead and have your controller action populate and pass this view model to the view:
public ActionResult Index()
{
IEnumerable<Customer> customers = ... fetch the domain model from your DAL or something
// map to a view model:
var viewModel = new MyViewModel
{
Customers = customers.Select(x => new SelectListItem
{
Value = x.CustID,
Text = string.Format("{0}%#%{1}%#%{2}", x.CustID, x.LName, x.FName)
})
};
// pass the view model to the view:
return View(viewModel);
}
and inside the view, use the DropDownListFor helper when you need to generate a dropdown list:
@Html.DropDownListFor(x => x.CustomerId, Model.Customers)
Upvotes: 4