2

enter image description here

I'm working on a page where the multiple radio button groups are loaded from code. It can 2,3,4.... and so each radio button group can contain one or more radio button as shown in the pic.

The workflow is user selects a radio button and the grid below filters the result as more and more radio buttons are clicked, the grid results gets reduced until the user gets what he wants.

I need to capture all the radio buttons that were clicked in the Controller action.

public ActionResult index(IEnumerable<string> selectedRadioButtons)
{
}

This doesn't seem to work. Any idea how I can implement this.

Model

public class Person
{
     public string Name {get;set;}
     public IEnumerable<FavoriteGroup> Favorites {get;set;}
}

public class FavoriteGroup
{
    public string GroupName {get;set;}
    public IEnumerable<KeyValuePair> Options {get;set;}
}

enter image description here

1
  • You need to show your view. Commented Jan 11, 2016 at 22:24

1 Answer 1

2

As long as you manipulate the form field name's to match with your view model properties/hierarchy-structure, It will work.

Let's add a new property to your FavoriteGroup class to store the selected radio button value.

public class FavoriteGroup
{
    public string GroupName { get; set; }
    public IEnumerable<KeyValuePair<int, string>> Options { get; set; }
    public int SelectedAnswer { set; get; }
}

And in your view,

@model YourNameSpaceHere.Person
@using (Html.BeginForm())
{
    var qCounter = 0;

    foreach (var favoriteGroup in Model.Favorites)
    {    
        <h4>@favoriteGroup.GroupName</h4>

        @Html.HiddenFor(f => f.Name)
        foreach (var option in favoriteGroup.Options)
        {
            @Html.Hidden("Favorites[" + qCounter + "].GroupName", favoriteGroup.GroupName)

            @Html.RadioButton("Favorites[" + qCounter + "].SelectedAnswer", option.Key)
            <span>@option.Value</span>

        }
        qCounter++;
    }    
    <input type="submit" />
}

Assuming you are sending a valid Person object with the properties filled with some data.

And your HttpPost action method will be,

[HttpPost]
public ActionResult Index(Person vm)
{
    foreach (var group in vm.Favorites)
    {
        var groupName = group.GroupName;
        var selected = group.SelectedAnswer;
       //do something with these 
    }
   // to do : Return something
}

Another solution is to use EditorTemplates in which you do not need to manipulate the field names like what we did above.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.