简体   繁体   English

ASP.NET Core 6 MVC 中新 SelectListItem 中的条件逻辑

[英]Conditional logic in new SelectListItem in ASP.NET Core 6 MVC

I want to set the text value of a SelectListItem .我想设置SelectListItem的文本值。

What's the easiest way?最简单的方法是什么? I've tried variations of the following with no luck.我尝试了以下变体但没有运气。

 public IActionResult Upsert(int? id)
 {
    RegistrationVM registrationVM = new()
    {
        Registration = new(),
        AttendedList = _unitOfWork.Registration.GetAll().Select(i => new SelectListItem
        {
            if (i.ATTENDED == 0)
            {
                Text = "No"
            }
            else
            {
                Text = "Yes"
            },
            Value = i.ATTENDED.ToString()
        })
    };
}

You need an expression that resolves to a value, rather than a set of statements that form a control flow block.您需要一个解析为一个值的表达式,而不是一组形成控制流块的语句。 The simplest is, in my opinion, a ternary:在我看来,最简单的是三元组:

    AttendedList = _unitOfWork.Registration.GetAll().Select(i => new SelectListItem
    {
        Text = i.ATTENDED == 0 ? "No" : "Yes",
        Value = i.ATTENDED.ToString()
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM