2012-07-23 42 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