0

I have an unordered list with multiple list items where in each one they have a checkbox and a dropdownlist.

I want to get at the selected dropdown value for each dropdown that corresponds to a checkbox that was checked.

I can easily get at the checkboxes that were checked by having a controller parameter of int[] checkboxes. This gives the value of every checkbox that was checked.

Now, how can I get the selected value of the dropdowns that are next to these checked checkboxes.

Will I have to use javascript to capture the selected values and pass it to the controller?

1 Answer 1

1

You need to work with more complex model than just int[] in a controller:

public class CheckedListModel
{
    public bool IsChecked { get; set; }

    public int SelectedValue { get; set; }

    public SelectList Items { get; set; }
}

A sample view to render a list of such models:

@model CheckedListModel[]

@using (Html.BeginForm())
{
    <ul>
        @for (int i = 0; i < Model.Length; i++)
        {
            <li>
                @Html.CheckBoxFor(m => m[i].IsChecked)
                @Html.DropDownListFor(m => m[i].SelectedValue, Model[i].Items)
            </li>
        }
    </ul>
    <input type="submit" value="Save"/>
}

And the controller:

    [HttpGet]
    public ActionResult Index()
    {
        return View(new CheckedListModel[]
            {
                //Sample data
                new CheckedListModel{Items = new SelectList(new []
                    {
                        new SelectListItem{Text = "Text 1", Value="1"},
                        new SelectListItem{Text = "Text 2", Value="2"},
                        new SelectListItem{Text = "Text 3", Value="3"},
                    }, "Value", "Text")},
                new CheckedListModel{Items = new SelectList(new []
                    {
                        new SelectListItem{Text = "Text 5", Value="5"},
                        new SelectListItem{Text = "Text 6", Value="6"},
                    }, "Value", "Text")},
            });
    }

    [HttpPost]
    public ActionResult Index(CheckedListModel[] models)
    {
        IEnumerable<CheckedListModel> checkedItems = models.Where(m => m.IsChecked);
        //Rest of the code
    }
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.