使用Viewbag

时间:2019-11-14 23:59:51

标签: c# html asp.net-mvc 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>
}

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

  

错误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的第二个参数传递什么参数,以便在我提交时收到正确的值?

2 个答案:

答案 0 :(得分:1)

您直接在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>
}

答案 1 :(得分:0)

遵循chandrakant的回答,它使我走上了正确的道路。但是,他的回答使我犯了一个错误:

  

'无法转换类型   'System.Collections.Generic.List <\ TheNextUp.Model.UpListConfig>'   'System.Collections.Generic.List <\ System.Web.Mvc.SelectListItem>''

不得不这样铸造我的

@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,以便传递该单选按钮的值。