【问题标题】:Model binding dynamic Radio Button value using Viewbag使用 Viewbag 绑定模型动态 Radio Button 值
【发布时间】:2020-03-11 02:17:14
【问题描述】:

我正在使用 razor 生成单选按钮。但是,当我提交时,传递的值是

System.Web.Mvc.SelectList

而不是像"1234" 这样的实际字符串值(这是我所期望的)

这是我的html代码

@foreach (var lists in ViewBag.Lists)
{
    <span class="nowrap">
        @Html.RadioButtonFor(m => m.Lists, (SelectList)ViewBag.Lists, new { id = "list" + lists.Value)

        <label for="list@(lists.Value)" style="color:#808080;font-weight:100">@lists.Text</label>
    </span>
}

我尝试用lists.Value 替换(SelectList)ViewBag.Lists,但它会用

错误 CS1929 'HtmlHelper' 不包含 'RadioButtonFor' 和最好的扩展方法重载 'InputExtensions.RadioButtonFor(HtmlHelper, Expression>, object, object)' 需要一个 'HtmlHelper' 类型的接收者

这里是存储库方法

public SelectList GetListsByLocation(int locationId)
{
    using (var ctx = new V4Entities())
    {
        var query = (from l in ctx.FooBarConfig
        where l.IsActive
        where l.LocationId == locationId
        orderby l.ServiceTypeId, l.Name
        select l);
        return new SelectList(query.ToList(), "UplistConfigId", "Name");
    }
}

这是在页面的控制器方法中分配的。

ViewBag.Lists = _upListConfigRepo.GetListsByLocation(TnuSession.Current.LocationId);

我的问题是,我应该为 Html.RadioButtonFor 的第二个参数传递什么参数,以便在提交时收到正确的值?

【问题讨论】:

    标签: c# html asp.net-mvc razor


    【解决方案1】:

    按照 chandrakant 的回答,它引导我走上了正确的道路。然而,他的回答让我犯了一个错误:

    '不能转换类型 'System.Collections.Generic.List' 到 'System.Collections.Generic.List''

    我不得不这样投

    @foreach (var lists in (SelectList)ViewBag.lists)
    {
        <span class="nowrap">
            @Html.RadioButtonFor(m => m.Lists, lists.Value, new { id = "list" + lists.Value, name = "Lists", @value = lists.Value, @text = lists.Text })
            <label for="list@(lists.Value)" style="color:#808080;font-weight:100">@lists.Text</label>
        </span>
    }
    

    那么,RadioButtonFor 的第二个参数必须是 lists.Value 才能传递该单选按钮的值。

    【讨论】:

      【解决方案2】:

      您在 Radiobuttonfor() 中直接使用 ViewBag.List 变量,这是错误的

      下面的代码应该适合你

      @foreach (var lists in (List<SelectListItem>)ViewBag.lists.Items)
      {
          <span class="nowrap">
              @Html.RadioButtonFor(m => m.Lists, lists, new { id = "list" + lists.Value })
      
              <label for="list@(lists.Value)" style="color:#808080;font-weight:100">@lists.Text</label>
          </span>
      }
      

      【讨论】:

      • 你很亲密,先生!通过在 foreach 循环中投射 ViewBag,您绝对引导我走上了正确的道路。我不得不投我的(SelectList)ViewBag.lists。感谢您的时间和帮助!
      猜你喜欢
      • 1970-01-01
      • 2017-07-06
      • 2021-07-26
      • 2011-05-20
      • 2015-11-12
      • 1970-01-01
      • 1970-01-01
      • 2019-09-09
      • 2022-01-07
      相关资源
      最近更新 更多