【问题标题】:Multiple form elements binding to one model attribute多个表单元素绑定到一个模型属性
【发布时间】:2011-09-01 08:52:21
【问题描述】:

我有模特

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)%>

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

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

在控制器方面,我对如何绑定它有点迷茫?

【问题讨论】:

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


    【解决方案1】:

    型号:

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

    控制器:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-04
      • 2022-01-01
      • 1970-01-01
      • 2018-06-04
      • 2023-04-04
      • 2013-11-05
      • 2020-12-07
      相关资源
      最近更新 更多