【发布时间】:2017-03-23 16:55:40
【问题描述】:
这是我的代码,应该显示模式中的一些数据。目前我没有数据:
<div class="desc-plus-products align-centre ">
@{
var TheString = "";
if (item.Name.Length == 0)
{
TheString = "Empty Name String";
}
else
{
TheString = item.Name;
}
var maxLength = 20;
var trimmedString = TheString.Substring(0, Math.Min(TheString.Length, maxLength));
trimmedString = trimmedString.Substring(0, Math.Min(trimmedString.Length, trimmedString.LastIndexOf(" ")));
}
<p>@trimmedString</p>
<p>£@item.Price</p>
</div>
错误如下:
Length cannot be less than zero.
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: Length cannot be less than zero.
Parameter name: length
Source Error:
Line 112:
Line 113: var trimmedString = TheString.Substring(0, Math.Min(TheString.Length, maxLength));
Line 114: trimmedString = trimmedString.Substring(0, Math.Min(trimmedString.Length, trimmedString.LastIndexOf(" ")));
Line 115: }
Line 116: <p>@trimmedString</p>
Source File: D:\Websites\websitename\Views\Home\Index.cshtml Line: 114
我原以为if statement 会使错误消失,因为我检查字符串是否为空,如果是,我将字符串设置为临时字符串以与length 方法一起使用。
【问题讨论】:
-
使用 string.IsNullOrWhiteSpace 而不是检查字符串长度。
-
String.LastIndexOf(string) 如果未找到子字符串,则返回 -1。
-
如果您实际调试过代码,这将很容易发现,您是否尝试过这样做?
-
它仍然可以回答,如果它被删除,那么什么都不会丢失。如果没有,那么至少有一个与之相关的答案。我看不出故意不回答问题的意义,即使它的质量很差。这不会改变最初提出问题的事实。
-
无意冒犯,但您是在鼓吹在编辑该问题以改进问题后浪费时间回答一个糟糕的问题,并继续在其上发布 cmets。我想这归结为每个人都认为是浪费时间,对我来说,回答一个问题,即使是一个可怜的问题,如果它对某人有帮助不是浪费时间 - 至少对我来说。
标签: c# asp.net-mvc razor