[英]How to send selected radiobutton value together with html.actionlink in MVC 5
I did sorting by initial letters in my MVC 5 application. 我在MVC 5应用程序中按首字母进行了排序。 Now I would like to add radio buttons to determine whether it will sort by name or last name.The problem is that I do not know how to send value of a selected radiobutton together with Html.ActionLink (after the user clicks on it) to controller.
现在我想添加单选按钮以确定它是按名称还是姓氏排序。问题是我不知道如何将所选单选按钮的值与Html.ActionLink(在用户单击后)一起发送给控制器。
I hope it is understandable what I want to achieve. 我希望我能实现的目标是可以理解的。
View: 视图:
using (Html.BeginForm())
{
@Html.RadioButton("sortButton", "FirstName", true) <span>First Name</span>
@Html.RadioButton("sortButton", "LastName") <span>Last Name</span>
<div class="form-inline">
<div class="form-group">
<div class="form-horizontal">
@Html.ActionLink("ALL", "Index", new { sortLetter = "" }) |
@Html.ActionLink("A", "Index", new { sortLetter = "A" }) -
@Html.ActionLink("B", "Index", new { sortLetter = "B" }) -
@Html.ActionLink("C", "Index", new { sortLetter = "C" }) -
@Html.ActionLink("D", "Index", new { sortLetter = "D" }) -
etc...
</div>
</div>
</div>
}
Controller: 控制器:
public class HomeController : Controller
{
private UsersContext ctx = new UsersContext();
public ActionResult Index(string sortLetter, string sortButton)
{
var contacts = from s in ctx.Users
select s;
// Sorting A - Z
if (sortLetter != null)
{
if (sortButton == "FirstName"
{
contacts = contacts.Where(o => o.FirstName.ToUpper().StartsWith(sortLetter));
}
else
{
contacts = contacts.Where(o => o.LastName.ToUpper().StartsWith(sortLetter));
}
}
return View(contacts.ToList());
}
}
You might need to go with workaround using jquery for this 您可能需要使用jquery解决此问题
$(function () {
$('.form-horizontal a').on('click', function () {
var url = $(this).attr('href'),
selectedSortLetter = $('input[type="radio"][name="sortButton"]:checked').val();
$(this).attr('href', url + '?sortLetter=' + selectedSortLetter);
//or directly browse to url like below.
location.href = url + '?sortLetter=' + selectedSortLetter;
});
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.