c# - mvc中只能使用赋值、调用、自增、自减、new对象表达式作为语句

标签 c# asp.net-mvc compiler-errors controller

我正在尝试通过在 Controller 中使用内联 if 来从数据库中的一个表中获取金额

    public ActionResult IfPaid(int id)
    {
        Ref_ViewModel = new View_model.View_Model();
        Ref_ViewModel.GetAllCustomers(id).Any(p => p.Paid == false) ? RedirectToAction("Pay", "Account") : RedirectToAction("Download");
    }

我在最后一行收到此错误

Only assignment, call, increment, decrement, and new object expressions can be used as a statement

我们如何解决这个问题?

最佳答案

您应该添加一个返回语句:

public ActionResult IfPaid(int id)
{
    Ref_ViewModel = new View_model.View_Model();
    return Ref_ViewModel.GetAllCustomers(id).Any(p => p.Paid == false)
         ? RedirectToAction("Pay", "Account")
         : RedirectToAction("Download");
}

正如错误消息所示,三元运算符本身并不是一个语句。它可以是另一个语句的一部分 - 例如上面的 return 语句,或者赋值语句

   int value = condition ? 0 : 42;

进一步阅读:Statements (C# Programming Guide)

关于c# - mvc中只能使用赋值、调用、自增、自减、new对象表达式作为语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43934299/

相关文章:

c# - 如何在 Xamarin.iOS 中向后滑动?

c# - DataTable 行属性

c# - 升级到 MVC3。找不到 ashx 资源。路由问题?

visual-studio-2010 - 如何修复 Entity Framework 4.1 模型模板中缺失的类型/命名空间错误?

.net - 阻止 .NET 代码调用特定方法?

c# - 在特定设备中播放声音

c# - 如何在没有任何数字作为字段的情况下覆盖 GetHashCode()?

c# - ASP.NET 完全模块化设计——怎么样?

c# - 没有实现 UoW 或存储库的 EF 是否正确?

C++ 编译错误 C2146 和 C4430