【问题标题】:How do I keep the clicked state of a checkbox in asp.net如何在asp.net中保持复选框的单击状态
【发布时间】:2013-04-26 06:45:25
【问题描述】:

在我的 mvc4 应用程序中保持我的复选框状态确实有问题。我正在尝试将其值发送到我的控制器逻辑,并根据给定值刷新模型中的列表,然后再将模型发送回具有新值的视图。鉴于我的复选框是“在列表中显示禁用的元素”类型的功能,我需要它能够打开和关闭。我已经看到了很多不同的解决方案,但我似乎无法让它们发挥作用:(

这是我的部分观点:

@model MyProject.Models.HomeViewModel

<div class="row-fluid">
    <div class="span12">
        <div class="k-block">
            <form action="~/Home/Index" name="refreshForm" method="POST">
                <p>Include disabled units: @Html.CheckBoxFor(m => m.Refresh)</p>
                <input type="submit" class="k-button" value="Refresh" />
           @* KendoUI Grid code *@
        </div>
    </div>

HomeViewModel:

public class HomeViewModel
{
    public List<UnitService.UnitType> UnitTypes { get; set; }
    public bool Refresh { get; set; }
}

HomeViewController 需要一些重构,但这将是一项新任务

[HttpPost]
public ActionResult Index(FormCollection formCollection, HomeViewModel model)
{
    bool showDisabled = model.Refresh;

    FilteredList = new List<UnitType>();
    Model = new HomeViewModel();
    var client = new UnitServiceClient();
    var listOfUnitsFromService = client.GetListOfUnits(showDisabled);

    if (!showDisabled)
    {
        FilteredList = listOfUnitsFromService.Where(unit => !unit.Disabled).ToList();
        Model.UnitTypes = FilteredList;

        return View(Model);
    }

    FilteredList = listOfUnitsFromService.ToList();
    Model.UnitTypes = FilteredList;

    return View(Model);
}

【问题讨论】:

  • 将代码清理到尽可能小的测试用例中,这样任何人都可以更轻松地查看它。前任。 “TmpList”没有在任何地方定义。
  • 现在我开始编辑这篇文章。只是需要一些时间来清理它。

标签: c# asp.net-mvc asp.net-mvc-4 kendo-ui


【解决方案1】:

您将Model 返回到您的视图,因此您的Model 属性将被填充,但您的复选框值不是您模型的一部分!解决方案是完全取消 FormCollection 并将复选框添加到您的视图模型:

public class HomeViewModel
{
    ... // HomeViewModel's current properties go here
    public bool Refresh { get; set; }
}

在你看来:

@Html.CheckBoxFor(m => m.Refresh)

在您的控制器中:

[HttpPost]
public ActionResult Index(HomeViewModel model)
{
    /* Some logic here about model.Refresh */
    return View(model);
}

顺便说一句,我看不出您为什么要像现在一样将此值添加到会话中(除非您发布的代码中有些内容不明显。

【讨论】:

    猜你喜欢
    • 2012-10-23
    • 2017-12-25
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多