【问题标题】:RadioButtonFor not binding with partial viewRadioButtonFor 不绑定局部视图
【发布时间】:2015-12-09 15:22:00
【问题描述】:

我的 RadioButtonFor 绑定到我的后控制器操作时遇到问题。见下文。

主视图 - 调用一个动作来加载部分视图并用表单包围它

@using (Html.BeginForm("FilterPlaceInPriorPosition", "Placements", FormMethod.Post))
{
    @Html.Action("AdvancedSearch", "Home", new { Area = "Common", advancedSearchModel = Model.AdvancedSearch })
}

AdvancedSearch 部分控制器操作

public ActionResult AdvancedSearch(AdvancedSearch advancedSearchModel)
    {

       return PartialView("_AdvancedSearch", advancedSearchModel);
    }

部分视图 - _AdvancedSearch.cshtml

@model AdvancedSearch
<div class="row">
        <div class="col-sm-4">
            @Html.TextBoxFor(model => model.Search, new { @class = "form-control no-max-width" })
        </div>
        <div class="col-sm-8">

                @Html.RadioButtonFor(model => model.MyActiveStudents, true, new {Name = "studentTypeRadio"}) <label for="MyActiveStudents">My active students</label>

                @Html.RadioButtonFor(model => model.AllActiveStudents, true, new {Name = "studentTypeRadio"}) <label for="AllActiveStudents">All active students</label>

        </div>
    </div>

发布控制器操作 -FilterPlaceInPriorPosition

[HttpPost]
        public ActionResult FilterPlaceInPriorPosition(AdvancedSearch filter)
        {
            return RedirectToAction("PlaceInPriorPosition", filter);
        }

AdvancedSearch.cs 类

public class AdvancedSearch
{
    public bool MyActiveStudents { get; set; }
    public bool AllActiveStudents { get; set; }

如果您查看图像,您会看到文本框文本已绑定,但两个单选按钮没有。 debugging results image

【问题讨论】:

    标签: c# asp.net-mvc razor partial-views radiobuttonfor


    【解决方案1】:

    您正在显式更改无线电输入的名称属性。然后,该值将被发送回studentTypeRadio MyActiveStudentsAllActiveStudents。由于您的模型上没有任何内容与此匹配,因此该值被简单地丢弃。

    相反,你应该有类似的东西:

    public class AdvancedSearch
    {
        public bool OnlyMyActiveStudents { get; set; } // default will be `false`
    }
    

    然后在你的部分:

    @Html.RadioButtonFor(m => m.OnlyMyActiveStudents, true, new { id = "MyActiveStudents" })
    <label for="MyActiveStudents">My active students</label>
    
    @Html.RadioButtonFor(m => m.OnlyMyActiveStudents, false, new { id = "AllActiveStudents" })
    <label for="AllActiveStudents">All active students</label>
    

    另外,FWIW,在这里使用子动作是没有意义的。如果您只想将实例传递给局部视图,则只需 Html.Partial 即可完成此操作,而无需子操作的所有不必要开销:

    @Html.Partial("_AdvancedSearch", Model.AdvancedSearch)
    

    【讨论】:

    • 有没有办法让两个以上的单选按钮拥有一个名称属性?在未来,我将拥有比我列出的更多的东西。例如,我将添加其他按钮以进行更多过滤。我需要具有不同属性名称但属于同一组的收音机。 @伊戈尔
    • @Jimmy,我建议您使用 enum 而不是 bool 属性。 stackoverflow.com/questions/18542060/…
    • @Jimmy - 一组具有相同名称的单选按钮表示同一属性的多个互斥值。在模型中,您只需要一个属性。它可以是布尔值(如果只有两个可能的值)、整数、枚举、字符串。
    • 是的。两个收音机,使用布尔值。对于两个以上,使用枚举。无论哪种方式,每个无线电组都应该只有一个属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 2015-04-09
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    • 2016-06-23
    相关资源
    最近更新 更多