@Html.RadioButtonFor(model => model.authType, "email", Model.authType == "email")Email
@Html.RadioButtonFor(model => model.authType, "sms", Model.authType == "sms")SMS
在上面的代码中,单选按钮是根据条件
Model.authType == "email"
或Model.authType == "sms"
自动检查的,但我想添加两个条件来自动检查单选按钮。
例如我尝试添加条件,例如
Model.authType == "email" && !string.IsNullOrEmpty(Model.email)
但第二个条件不执行,复选框根据第一个条件自动检查并忽略第二个条件。
如果我只使用单一条件,效果很好。
我尝试了这段代码,但它不起作用:
@Html.RadioButtonFor(model => model.authType, "email", Model.authType == "email" && !string.IsNullOrEmpty(Model.email) )Email
@Html.RadioButtonFor(model => model.authType, "sms", Model.authType == "sms" && !string.IsNullOrEmpty(Model.phone) )SMS
我还尝试将这两个条件分配在一个布尔变量中并使用该变量,但仍然不起作用。
我有下面的代码,根据我的测试,无论我是否有像
Model.IsEnrolled== "All"
这样的代码,“全部”的单选按钮将始终被选中。同样,如果我设置Model.IsEnrolled== "Yes"
,则“是”单选按钮将被选中。我认为你可以将验证放在控制器中而不是 cshtml 中。您可能有与我类似的代码,其中 authType
的设置值类似于 model.authType == !string.IsNullOrEmpty(Model.email) ? "email" : "sms"
。然后,当电子邮件为空时,将选中短信单选按钮。反正就看你自己的业务逻辑了。
<form asp-controller="Movies" asp-action="Index" method="get">
<p>
Title: <input type="text" asp-for="SearchString" />
Gender:
<span class="col-md-10">
<span style="margin-left:10px;">
@Html.RadioButtonFor(model => model.IsEnrolled, "Yes") Enrolled
</span>
<span style="margin-left:10px;">
@Html.RadioButtonFor(model => model.IsEnrolled, "No") Not Enrolled
</span>
<span style="margin-left:10px;">
@Html.RadioButtonFor(model => model.IsEnrolled, "All") All
</span>
</span>
<input type="submit" value="Filter" />
</p>
</form>
public async Task<IActionResult> Index(string isEnrolled)
{
var movies = from m in _context.Movie
select m;
if (!string.IsNullOrEmpty(isEnrolled))
{
movies = movies.Where(x => x.Genre == "asdf");
}
var movieGenreVM = new MovieGenreViewModel
{
Movies = await movies.ToListAsync(),
IsEnrolled = string.IsNullOrEmpty(isEnrolled) ? "All" : isEnrolled
};
return View(movieGenreVM);
}