How to send selected radiobutton value together with html.actionlink in MVC 5

1.6k views Asked by At

I did sorting by initial letters in my MVC 5 application. 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.

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

There are 1 answers

0
Nitin Varpe On

You might need to go with workaround using jquery for this

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