【发布时间】:2011-11-09 08:23:47
【问题描述】:
我的课程中有一些表示真或假的字段,但它有字符串值“T”或“F”。
如何将复选框绑定到这些字段?
【问题讨论】:
-
我已经更新了我的解决方案,以进一步解决您遇到的服务器端绑定问题。
标签: asp.net-mvc checkbox
我的课程中有一些表示真或假的字段,但它有字符串值“T”或“F”。
如何将复选框绑定到这些字段?
【问题讨论】:
标签: asp.net-mvc checkbox
您可以在 ASP.Net MVC Razor 中执行此操作
<input type="checkbox" name="someName" value="@Model.SomeValue"
@(Model.IsChecked == "T" ? "checked='checked'" : "") />
但是,这可能不是您想要的,因为您必须在服务器上进行一些手动工作才能找出“未选中”的值。
默认情况下,只有您选中的值会被发送到服务器。
Html.CheckBox 和 Html.CheckBoxFor 辅助方法都发出隐藏字段,以确保所有内容都正确绑定回您的模型。你可以很容易地模仿这种行为。
首先,您需要发出一个隐藏字段,该字段将绑定到服务器上的模型。
@Html.HiddenFor(model => model.StringBool, new { id = "_stringBool" })
接下来,您创建一个普通的 jane 复选框并设置初始状态以反映您的模型。
<input type="checkbox" id="myCheckBox" @(Model.StringBool == "T" ? "checked='checked'" : "") />
此复选框的唯一目的是代理值进出隐藏字段,以便您的模型将自动绑定到服务器上。这可以通过一些简单的 jQuery 来实现。
$("#myCheckBox").click(function () {
var isChecked = $(this).is(":checked");
$("#_stringBool").val(isChecked ? "T" : "F");
});
现在选中和取消选中该框将相应地设置绑定隐藏字段的值。当您发布到服务器时,您的值将通过模型绑定保留。
这不考虑验证。更改隐藏字段的值非常容易,因此请确保在服务器端正确验证!
【讨论】:
当你设置新的复选框项目的检查状态时,只要放一个if语句:
checkBox1.Checked = (stringValue == "T") ?真:假;
【讨论】:
我做了自己的扩展来解决这个问题。它在 razorview 中更整洁一些,有助于最大限度地减少 c# / razor 混合物。这是课程:
public static class CheckBoxExtensions {
public static MvcHtmlString ValueCheckbox<TModel>(this HtmlHelper<TModel> htmlHelper, string name, string value, bool isChecked, IDictionary<string, object> htmlAttributes, bool disabled = false)
{
string result = string.Format(CultureInfo.InvariantCulture,
"<input type=\"checkbox\" name=\"{0}\" value=\"{1}\" {2} {3} ",
name, value, (isChecked) ? "checked=\"checked\"" : "", (disabled) ? "disabled=\"disabled\"" : "");
if (htmlAttributes != null && htmlAttributes.Count > 0)
{
foreach (KeyValuePair<string, object> item in htmlAttributes)
{
result += string.Format(CultureInfo.InvariantCulture, "{0}=\"{1}\" ", item.Key, item.Value.ToString());
}
}
result += " />";
return new MvcHtmlString(result);
}
}
这就是我在 razorview 中所做的:
Html.ValueCheckbox("SelectedItems",
item.Number,
(Model.SelectedItems.Contains(item.Number)),
new Dictionary<string, object>() {
{ "data-disable-bubble", "true" },
{ "data-forms-enable-any-checked-checkbox", "true" }
}
)
别介意那些奇怪的 HtmlAttributes,我想我会把它们放在那里 :-)
【讨论】: