开发者

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 nee开发者_如何学Cd 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?


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');
        }
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜