日期:2014-05-18  浏览次数:20421 次

高分求解:匪夷所思的GridView数据绑定、FormatString和JS脚本问题
我在一个gridView里面有一个模板列,部分内容如下:
<asp:TemplateField   HeaderText= "详情 ">
        <ItemTemplate>
                <asp:Label   ID= "place "   runat= "server "   Text= ' <%#Bind( "单位 ")%> '> </asp:Label>
        </ItemTemplate>
        <ItemStyle   Width= "100px "   />
</asp:TemplateField>
这个单位字段可能因为长度过大而导致换行,影响视觉效果,因此有了一个JS函数limitStr来限制它的长度。该函数接受三个参数:第一个是要限制长度的字符串,在这里当然应该是{0},第二个是要限制到的长度(字节),指定为24,第三个是是(true)否(false)在被截断的字符串之后添加一个省略号。按照往常经验,这个模板列改为:
<asp:TemplateField   HeaderText= "详情 ">
        <ItemTemplate>
                <asp:Label   ID= "place "   runat= "server "   Text= ' <%#Bind( "单位 ", "&lt;script&gt;document.write(limitStr( '{0} ',24,true));&lt;/script&gt; ")%> '> </asp:Label>
        </ItemTemplate>
        <ItemStyle   Width= "100px "   />
</asp:TemplateField>

此时 <asp:Label....这句出错:

分析器错误  
说明:   在分析向此请求提供服务所需资源时出错。请检查下列特定分析错误详细信息并适当地修改源文件。  

分析器错误信息:   服务器标记的格式不正确。

疑为“ '{0} '”处单引号与“Text= '”处单引号冲突了,于是改为:

<asp:TemplateField   HeaderText= "详情 ">
        <ItemTemplate>
                <asp:Label   ID= "place "   runat= "server "   Text= ' <%#Bind( "单位 ", "&lt;script&gt;document.write(limitStr( "   &   chr(34)   &   "{0} "   &   chr(34)   &   ",24,true));&lt;/script&gt; ")%> '> </asp:Label>
        </ItemTemplate>
        <ItemStyle   Width= "100px "   />
</asp:TemplateField>

这时候更棘手的问题出现了,在IE中查看该页,VS和ASP.NET   Development   Server同时停止相应(CPU占用率很高);强制关闭后如果用VS打开此页,VS直接挂掉,必须用记事本将该句改回才能用VS打开。想了半天想不出这是个什么问题,麻烦各位大大会诊一下。解决后另有一百分作为感谢。

------解决方案--------------------
看看你的数据是不是很多。
------解决方案--------------------
为什么不在后台做呢?
------解决方案--------------------
在后台写处理的方法
.cs文件代码:

public string limitStr(string text,int length)
{
return text.SubString(0,length) + "... ";
}
<asp:TemplateField HeaderText= "详情 ">
<ItemTemplate>
<asp:Label ID= "place " runat= "server " Text= ' <%# limitStr(Bind( "单位 ").ToString(),24)%> '> </asp:Label>
</ItemTemplate>
<ItemStyle Width= "100px " />
</asp:TemplateField>
------解决方案--------------------
前台方便?那出错了你怎么调试?能够后台去编写程序的尽量不要放到前台来,因为这样的逻辑性比较强!
------解决方案--------------------
try ->

<asp:Label ID= "place " runat= "server " Text= ' <%# Eval( "单位 ", " <script> document.write(limitStr( '{0} ',24,true)) <