RadioButtonFor 不与局部视图绑定

RadioButtonFor not binding with partial view

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

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

@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 class

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

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

您正在明确更改无线电输入的名称属性。然后,该值将回传到 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)