2012-07-23 46 views
5

我正在編寫一個ASP.NET MVC應用程序。我是初學者,所以我確信這很容易。我引用了ASP.NET MVC - How to get checkbox values on post,但代碼不再可用,使其成爲無用的代碼。獲取回發的複選框值ASP.NET MVC

這是我的視圖:

@using (@Html.BeginForm("Promote", "FPL", FormMethod.Post)) 
{ 
<div data-role="fieldcontain"> 
<fieldset id="PromotionInfo" name="PromotionInfo"> 
<legend><b>@Model.itemType Promotion Details</b></legend> 
    <label for="TargetDate">Target Date: </label> 
    <input type="date" id="TargetDate" data-role="datebox" data-options='{"mode": "flipbox"}' /> 

    <label for="EmailCC">Email cc List: </label> 
    <input type="email" id="EmailCC" /> 

    <div data-role="fieldcontain"> 
    <fieldset data-role="controlgroup"> 
    <legend>Choose Destination Server(s): </legend> 

    @foreach (DataRow server in Model.destinationServerList.Rows) 
    { 
    <label for="@server.ItemArray[0]">@server.ItemArray[1]</label> 
    <input type="checkbox" name="destinationServerSID" id="@server.ItemArray[0].ToString()" /> 
    } 

    </fieldset> 
    </div> 
</fieldset> 

</div> 

<input type="submit" value="Submit" /> 
} 

這是我的控制器:

public ActionResult Promote(string id) 
    { 
     //Model(item) construction occurs here 

     return View(item); 
    } 

    [HttpPost] 
    public ActionResult Promote(FormCollection collection) 
    { 
     try 
     { 
      string[] test = collection.GetValues("destinationServerSID"); 
     } 
     catch (Exception ex) 
     { 
      return null; 
     } 
    } 

測試[]變量包含2項數組,兩者都具有「開」,不過值,我的物品清單是超過2項。它僅包含您選擇的每個值的「開」,但不包含「關」值。我需要複選框的實際值(id字段)。

回答

3

ID不會發布到服務器。只有在複選框被選中時,名稱和值纔會發佈到服務器。

嘗試使用@server.ItemArray[0].ToString()設置value屬性。

<input type="checkbox" name="destinationServerSID" value="@server.ItemArray[0].ToString()" /> 
+1

哇,我不能相信我錯過了...非常感謝你,這就是我所需要的。 – 2012-07-23 19:03:36

3

默認的HTML發佈行爲不發送未經檢查的框的值。您可以使用Html.CheckboxFor方法,它會生成所有必需的輸入以始終發佈值。

+0

這也會起作用,但是關於將它作爲值而不是id傳遞給我的答案是我所需要的。謝謝你的回答! – 2012-07-23 19:04:25