2013-04-26 53 views
1

我确实在我的复选框的状态保持在我的mvc4应用程序中存在问题。我试图将它的值传递给我的控制器逻辑,并根据给定的值在我的模型中刷新一个列表,然后再将模型返回到具有新值的视图。鉴于我的复选框是“在列表中显示禁用的元素”类型的功能,我需要它可以打开和关闭。我已经看到了这许多不同的解决方案,但我似乎无法让他们的工作:(如何保持asp.net中复选框的点击状态

这是我的观点的一部分:

@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); 
} 
+1

将代码清理成尽可能最小的测试用例,让任何人都可以轻松查看它。防爆。 “TmpList”没有在任何地方定义。 – 2013-04-26 07:03:37

+0

现在编辑这个职位,我得到它的工作。只需要一些时间来清理它。 – 2013-04-26 07:30:38

回答

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); 
} 

作为除此之外,我看不出有什么理由要你像现在这样将此值添加到会话中(除非在你发布的代码中没有明显的东西)

相关问题