Multiple form elements linked to the same model attribute

I have a model

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

In my opinion, I need to present two switches and a drop-down list to the user, while the drop-down list will act as the third switch 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 presentation, I'm sure jQuery can make sure that baronly one value is selected. However, if this can be avoided, it will be even better.

On the controller side, I lost myself a bit from how I'm going to tie this up?

+3
source share
1 answer

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" />
<% } %>

, javascript, , , , .

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

    $('#barDDL').change(function () {
        if ($(this).val() != '') {
            $('#barA, #barB').removeAttr('checked');
        }
    });
});
+1

All Articles