I have a server side object.
public class OptionRelation
{
public intOptionId { get; set; }
public string Type { get; set; }
public string Child { get; set; }
public string Peer { get; set; }
}
Inside of my view, I do the following:
//where relations is a List<OptionRelation>
var a = relations.FindAll(r => r.OptionId == option.OptionID);
string data_relation = "";
if(a.Count > 0)
{
data_relation = "data-relation=" + Json.Encode(a);
}
<input type="checkbox" @data_relation />
Attribute @data gets populated the way I expect most of the time. However, sometimes it breaks. If I open it in FireBug, the attributes of the <input> are all garbage. The only thing I can think of is that when it breaks the length of data-relation is slightly longer then the rest of the cases. Particularly, it breaks when data-relation should be:
data-relation="[{"OptionId":80,"Type":"required_1","Child":"#1625, #1626, #1627","Peer":""}]"
Any ideas why this is breaking?
SOLUTION: I ended up rewriting tons of code and finally getting it to work using custom HTML helper and partially utilizing Darin’s code for HTML helper.
You need to use
Html.Rawin the attribute to avoid Razor performing double HTML encoding, just like this:This being said, writing so much C# code in a view is probably one of the worst things you could do in an ASP.NET MVC application. It’s a horrible to look and maintain. That’s not what views are supposed to do. That’s what custom HTML helpers might be useful. So why spaghettifying your views when you can simply write the following
That kind of looks better compared to the previous abomination, doesn’t it?
And here’s what I mean by the custom helper: