c# - 绑定(bind)到一个模型属性的多个表单元素

标签 c# asp.net-mvc-2 model-binding

我有一个模型

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

在我看来,我需要向用户展示两个单选按钮和一个下拉列表,下拉列表充当组中的第三个单选按钮。

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

解决这个问题的最佳方法是什么?

对于 View ,我非常有信心 jQuery 可以确保只为 bar 选择一个值。但是,如果可以避免这种情况,那就更好了。

在 Controller 方面,我有点不知道如何绑定(bind)它?

最佳答案

型号:

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

查看:

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

关于c# - 绑定(bind)到一个模型属性的多个表单元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6118183/

相关文章:

javascript - 为什么对同一 ASP.NET MVC 操作的多个同时 AJAX 调用会导致浏览器阻塞?

c# - MVC 2 - 如何在创建方法中排除多列

ajax - 嵌套模型不绑定(bind)

asp.net-mvc - 如何在 asp.net MVC 中压缩内容?

asp.net-mvc-3 - 自定义模型绑定(bind)器仅适用于 MVC 应用程序的一个区域

asp.net-mvc - 将选择列表绑定(bind)到 mvc 3 中的模型

c# - 按下 mouse1 时播放声音,松开时停止声音

c# - 为什么我的堆上有两个空的 ThreadAbortExceptions?

c# - 每个表一个存储库还是每个功能部分一个?

c# - 在执行其他命令之前更改表单