菜鸟送分:这个函数的写法出错了
在a.aspx页面里接收了一个表单文本变量:
<%=Request.Form["a2"].Substring(0,10)%>
初用起来没问题,但是发现接收到的字符数小于10的时候就会出错:
Index and length must refer to a location within the string.
Parameter name: length
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.
Parameter name: length
这该怎么解决?
------解决方案--------------------那当然了,如果不够10个字符的话,你截取10个字符,肯定是超过索引了,你需要利用三元运算符做下判断
<%=(Request.Form["a2"].ToString().Length<10?Request.Form["a2"].ToString():Request.Form["a2"].ToString().Substring(0,10))%>
------解决方案--------------------索引越界,如果索引小于10是肯定会报错的
C# code
<%= Request.Form["a2"].ToString().Length >=10 ?Request.Form["a2"].Substring(0,10):
Request.Form["a2"].Substring(0,Request.Form["a2"].ToString().Length)
%>
------解决方案--------------------
如果在<%%>中的表达式代码过于复杂或冗长,还是建议所求值过程放到cs中去写。前台只需调cs中的方法就可以了
前台:
<%=GetA2Value() %>
后台cs中:
public String GetA2Value()
{
string v2 = Request.Form["a2"];
if (v2.Length > 10)
{
return v2.Substring(0, 10);
}
else
{
return v2;
}
}