复选框值未填充

时间:2014-09-15 10:33:27

标签: html asp.net asp.net-mvc asp.net-mvc-4 checkbox

我无法弄清楚为什么复选框没有显示值。原始代码是

<input type="checkbox" name="@row.Checkbox.Name" value="@row.Checkbox.Text"/>  

生成的HTML是

<input type="checkbox" name="chkparent" value=" I am the parent or legal guardian of the named child/children in my family membership and I give consent for them to take part in organised paddling activities (Kayak and/or Canoe) and I agree they will abide by the rules and regulations of Totnes Canoe Club at all times."/>

我试图将生成的html直接放在页面中,但它仍然没有显示值。 我看到的只是复选框。

4 个答案:

答案 0 :(得分:1)

checkbox的值不能用于显示文字。您需要在复选框旁边放置div或类似内容。像这样:

<div>
    <input type="checkbox" name="chkparent" style="float:left;margin-right:5px;"/>
    <div>
        I am the parent or legal guardian of the named child/children in my family membership and I give consent for them to take part in organised paddling activities (Kayak and/or Canoe) and I agree they will abide by the rules and regulations of Totnes Canoe Club at all times.
    </div>
</div>

如果你想让用户更容易,你应该在文本上附加一个点击处理程序(假设是jQuery):

<div>
    <input type="checkbox" id="chkparent" name="chkparent" style="float:left;margin-right:5px;"/>
    <div id="chktext" style="cursor:pointer;">
        I am the parent or legal guardian of the named child/children in my family membership and I give consent for them to take part in organised paddling activities (Kayak and/or Canoe) and I agree they will abide by the rules and regulations of Totnes Canoe Club at all times.
    </div>
</div>

<script>
    $(function(){
        $("#chktext").on("click", function(){
            if ($("#chkparent").is(":checked")) {
               $("#chkparent").prop("checked", false);
            } else {
               $("#chkparent").prop("checked", true);
            }
        });
    });
</script>

答案 1 :(得分:1)

最好为此创建一个带有bool属性的强类型视图模型,并使用显示名称进行装饰。

然后可以使用显示名称来呈现标签,如下所示:

查看模型

public class AViewModel
{
    [DisplayName("Selection 1")]
    public bool MySelection { get; set; }
}

查看

@Html.LabelFor(m => m.MySelection)
@Html.CheckBoxFor(m => m.MySelection)

Working example

答案 2 :(得分:1)

您可以在返回View之前验证控制器中的row.Checkbox值,以检查是否应该选中该复选框。

然后,将该信息分配给ViewBag变量:

ViewBag.checked = "checked";

在你的观点中:

<input type="checkbox" name="@row.Checkbox.Name" @ViewBag.checked/>

这将生成HTML

<input type="checkbox" name="@row.Checkbox.Name" checked/>

如果要选中复选框并

<input type="checkbox" name="@row.Checkbox.Name"/>

未选中复选框

答案 3 :(得分:1)

在不修改当前模型的情况下,代码应如下所示:

<label for="@row.Checkbox.Name">@row.Checkbox.Text @Html.CheckBox(row.Checkbox.Name, false)</label>