0

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']
4

2 回答 2

3

在@Html.TickWrap(Html.DisplayNameFor(m => Model.SampleDateTime)) 周围加上''(引号)

于 2013-04-18T11:00:46.337 回答
0

如果您想使用数据注释,您应该创建从属性类扩展的类。然后使用 PropertyInfo 反射获取值。

如果您想使用数据注释填充 jqGrid 的 colNames,我已经升级了我的 jq.grid 插件以支持数据注释,请查看此jq.grid以获取更多信息

于 2013-04-30T19:21:04.490 回答