I created an extension method that works when it is not included in a java script tag.
public static class ExtensionMethods
{
public static string TickWrap(this HtmlHelper source, MvcHtmlString mvcHtmlString)
{
return "'" + mvcHtmlString.ToHtmlString().Replace("'", "''") + "'";
}
}
usage in my view is as follows
@Html.TickWrap(Html.DisplayNameFor(m => Model.SampleDateTime))
All it's doing is grabbing the Display Name attribute of the Data Annotation listed below and displaying it as 'Date and Time' with the ticks around it.
[Display(Name = "Date and Time")]
public DateTime SampleDateTime {get; set;}
I can't seem to get this to work in a script tag however. I am getting a JavaScript critical error syntax error. Below is the script that is included in my view.
<script type="text/javascript">
$(function () {
var displayName = @Html.TickWrap(Html.DisplayNameFor(m => Model.SampleDateTime))
alert(displayName);
});
</script>
I'm guesing it has to do with the usage of the HtmlHelper in the script section? If so how can I use in the script section?
That is a simplified version of what I have going on but what I'm really trying to do is to populate the colNames for a jqGrid without having to hard code them in the javascript. I'd like to use the Data Annotations so I only have to change in one spot. The colNames for the jqGrid gets defined as
colNames: ['ParameterId','Location', 'Parameter Name', 'Date and Time', 'Parameter Value']