2013-04-26 83 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); 
} 

作爲除此之外,我看不出有什麼理由要你像現在這樣將此值添加到會話中(除非在你發佈的代碼中沒有明顯的東西)

相關問題