Joh*_*ter 2 c# asp.net-mvc asp.net-mvc-3
我在asp.net mvc应用程序中有folloiwng动作方法: -
public ActionResult CustomersDetails(long[] SelectRight)
{
if (SelectRight == null)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
RedirectToAction("Index");
}
else
{
var selectedCustomers = new SelectedCustomers
{
Info = SelectRight.Select(GetAccount)
};
return View(selectedCustomers);
}
return View();
}
Run Code Online (Sandbox Code Playgroud)
但是如果它SelectRight Array是空的,那么它将绕过if (SelectRight == null)检查,它将呈现CustomerDetails视图并在视图内的以下代码上引发异常
@foreach (var item in Model.Info) {
<tr>
Run Code Online (Sandbox Code Playgroud)
那么如何使空检查工作正常呢?
你必须返回结果RedirectToAction(..).
public ActionResult CustomersDetails(long[] SelectRight)
{
if (SelectRight == null)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
return RedirectToAction("Index");
}
else
{
'...
Run Code Online (Sandbox Code Playgroud)
您可以将条件更改为以下条件:
...
if (SelectRight == null || SelectRight.Length == 0)
...
Run Code Online (Sandbox Code Playgroud)
这应该有所帮助.
编辑
关于上面代码的重要注意事项是在c#中,或者运算符||是短路的.它看到数组为null(语句为true)并且不会尝试计算第二个语句(SelectRight.Length == 0),因此不会抛出NPE.