Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple form elements binding to one model attribute

I have a model

public class  Foo
{
  public string bar { get; set; }
  //Other stuff
}

In my view, I need to present the user with two radio buttons and a drop down list, with the drop down list acting as a third radio button in the group.

<%= Html.RadioButtonFor(m => m.bar, "A") %>
<%= Html.RadioButtonFor(m => m.bar, "B") %>
<%= Html.DropDownListFor(m => m.bar, ViewData["OtherUncommonOptions"] as SelectList)%>

What is the best approach to this problem?

For the view, I'm pretty confident that jQuery can make sure only one value is selected for bar. However if it's possible to avoid this that would be even better.

On the controller side, I'm a bit lost on how I'd go about binding this?

like image 551
AllDayer Avatar asked Aug 24 '26 03:08

AllDayer


1 Answers

Model:

public class Foo
{
    public string Bar { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewData["OtherUncommonOptions"] = new SelectList(
            Enumerable.Range(1, 5).Select(x => new SelectListItem 
            { 
                Value = x.ToString(), 
                Text = "item " + x 
            }),
            "Value",
            "Text"
        );
        return View(new Foo());
    }

    [HttpPost]
    public ActionResult Index(Foo model)
    {
        // model.Bar will contain the selected value here
        return View(model);
    }
}

View:

<% using (Html.BeginForm()) { %>
    <%= Html.RadioButtonFor(m => m.Bar, "A", new { id = "barA" }) %>
    <%= Html.RadioButtonFor(m => m.Bar, "B", new { id = "barB" }) %>
    <%= Html.DropDownListFor(
        m => m.Bar,
        ViewData["OtherUncommonOptions"] as SelectList,
        "-- value --",
        new { id = "barDDL" }
    ) %>

    <input type="submit" value="OK" />
<% } %>

And the last part would be to ensure using javascript that if one of the two radio buttons is selected the drop down list clears its value and if a value is selected in the drop down list the radio buttons are deselected.

$(function() {
    $('#barA, #barB').click(function () {
        $('#barDDL').val('');
    });

    $('#barDDL').change(function () {
        if ($(this).val() != '') {
            $('#barA, #barB').removeAttr('checked');
        }
    });
});
like image 93
Darin Dimitrov Avatar answered Aug 26 '26 16:08

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!