【问题标题】:How to send selected radiobutton value together with html.actionlink in MVC 5如何在 MVC 5 中将选定的单选按钮值与 html.actionlink 一起发送
【发布时间】:2015-08-25 08:27:19
【问题描述】:

我在 MVC 5 应用程序中按首字母排序。现在我想添加单选按钮以确定它是按名称还是姓氏排序。问题是我不知道如何将选定单选按钮的值与 Html.ActionLink 一起发送(在用户单击它之后)到控制器。

我希望我想要达到的目标是可以理解的。

查看:

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>
}

控制器:

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());
    }
}

【问题讨论】:

  • 需要使用javascript/jquery来构造url。 This answer 显示一个选项。

标签: c# asp.net-mvc actionlink razorengine


【解决方案1】:

您可能需要为此使用 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;
    });
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 2016-07-17
    • 2017-09-06
    • 2019-11-24
    相关资源
    最近更新 更多