我试图使用由两组两个单选按钮组成的表单进行发布,用于排序:Name/Rating
和Asc/Desc
使用它们,我想将2个布尔值发送给行动,但它不起作用。它是发布,但值没有通过,默认值总是传递。这里的问题是什么?
查看广播组:
<form action="../Restaurant/RestaurantsSort" method="post" class="btn-group" style="margin-top: 10px;">
// First radio group: Name / Rating
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label class="btn btn-secondary active">
<input type="radio" name="name" id="name" autocomplete="off" value=1 checked> <span class="glyphicon glyphicon-font"></span>Name
</label>
<label class="btn btn-secondary">
<input type="radio" name="name" id="name" autocomplete="off" value=0> <span class="glyphicon glyphicon-star"></span>Rating
</label>
</div>
// Second radio group: Asc / Desc
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label class="btn btn-secondary active">
<input type="radio" name="asc" id="asc" autocomplete="off" value=1 checked><span class="glyphicon glyphicon-arrow-up"></span> Asc
</label>
<label class="btn btn-secondary">
<input type="radio" name="asc" id="asc" autocomplete="off" value=0><span class="glyphicon glyphicon-arrow-down"></span> Desc
</label>
</div>
<input type="submit" id="list" class="btn btn-default btn-sm" value="Sort" style="margin-top: 5px;"/>
</form>
被召唤的行动:
// name is always true, asc is always true
[HttpPost]
public ActionResult RestaurantsSort(bool name = true, bool asc = true)
{
List<Restaurant> r = new List<Restaurant>();
switch (name)
{
case true:
switch (asc)
{
case true:
r = Restaurant.GetRestaurants("restaurants", "sortby", "name", "asc");
break;
case false:
r = Restaurant.GetRestaurants("restaurants", "sortby", "name", "desc");
break;
}
break;
case false:
switch (asc)
{
case true:
r = Restaurant.GetRestaurants("restaurants", "sortby", "rating", "asc");
break;
case false:
r = Restaurant.GetRestaurants("restaurants", "sortby", "rating", "desc");
break;
}
break;
}
TempData["restaurants"] = r;
return RedirectToAction("Restaurants");
}
答案 0 :(得分:0)
您的单选按钮的值为0
和1
。您无法将其中任何一个值绑定到bool
,该值接受true
或false
的值。
将单选按钮更改为
<input type="radio" name="name" id="name" autocomplete="off" value="true" checked />
<input type="radio" name="name" id="name" autocomplete="off" value="false" />
并同意asc
组。
但是你应该做的是拥有一个带属性的视图模型
public bool Name { get; set; }
public bool Asc { get; set; }
并使用强类型HtmlHelper
方法正确生成html
@Html.RadioButtonFor(m => m.Name, true, new { id = "" })
@Html.RadioButtonFor(m => m.Name, false, new { id = "" })
虽然名为Name
的属性应该是string
或enum
而不是bool
。