Reputation: 9691
I'm working on a project that is developed with C#, and my knowledge of C# isn't extensive, I just started to learn a few days ago :)
I came across this function :
public static IHtmlString RenderEditData<T>(string linkText) where T : CorinaEntity
{
string id = new IdGenerator().Generate<T>();
return new HtmlString(String.Format("<a href=\"#\" data-corina='{{ \"id\" : \"{0}\", \"clrType\" : \"{1}\" }}'>{2}</a>", id, typeof(T).AssemblyQualifiedName, linkText));
}
The above returns me a link tag, which was fine when I first started working on the project, but now I just need the data
attribute output as a string. So I just tried this :
public static String RenderEditData<T>() where T : CorinaEntity
{
string id = new IdGenerator().Generate<T>();
return String.Format("data-corina='{{ id : \'{0}\', 'clrType' : \'{1}\' }}", id, typeof(T).AssemblyQualifiedName);
}
The thing is that instead of resulting in this :
data-corina="{ "id" : "-[Model.Content]", "clrType" : "Model.Content, Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" }"
It returns something like this :
data-corina="'{" id="" :="" '-[model.content]',="" 'clrtype'="" 'model.content,="" model,="" version="1.0.0.0," culture="neutral," publickeytoken="null'" }=""
Obviously, there's some string escaping that I'm doing wrong, but I have no clue how to do it and not mess up the variables I need there. Can someone point me to the right solution for this ? Also am I doing it wrong if I changed public static IHtmlString RenderEditData
to public static String RenderEditData
, if the result I want is just a string ?
Upvotes: 1
Views: 2251
Reputation: 65049
MVC will escape any plain string you return. That is why your original function returns an IHtmlString
. When you return HtmlString
, the pipeline knows that you definitely expect the result to contain raw HTML.
Upvotes: 0
Reputation: 498904
Use the Html.Raw
helper to output raw HTML.
Alternatively, wrap the string in an HtmlString
:
public static String RenderEditData<T>() where T : CorinaEntity
{
string id = new IdGenerator().Generate<T>();
return new HtmlString(
string.Format("data-corina='{{ id : \'{0}\', 'clrType' : \'{1}\' }}",
id,
typeof(T).AssemblyQualifiedName));
}
Upvotes: 2