我需要幫助來構建一個獲取int值的CheckBoxFor。我怎樣纔能有一個CheckBoxFor使用int?
喜歡的東西:@ Html.CheckBoxForInt(M => m.foo.intValue)
應該檢查是否的intValue = 1,否則沒有檢查
THX
我需要幫助來構建一個獲取int值的CheckBoxFor。我怎樣纔能有一個CheckBoxFor使用int?
喜歡的東西:@ Html.CheckBoxForInt(M => m.foo.intValue)
應該檢查是否的intValue = 1,否則沒有檢查
THX
你爲什麼不在你的模型中暴露一個bool屬性來轉換爲/從int?
事情是這樣的:
public bool BoolValue
{
get { return IntValue == 1; }
set { IntValue = value ? 1 : 0;}
}
public int IntValue { get; set; }
然後,你可以用它來創建複選框
@Html.CheckBoxFor(m => m.foo.BoolValue)
出於某種原因,上面的反應給了我的錯誤,而是基於我已經改變了同樣的想法代碼是這樣的:
那對我有用。
下面是處理int類型的複選框幫手例如:
public static MvcHtmlString CheckBoxIntFor<TModel>(this HtmlHelper<TModel> html, Expression<Func<TModel, int>> expression, object htmlAttributes)
{
// get the name of the property
string[] propertyNameParts = expression.Body.ToString().Split('.');
// create name and id for the control
string controlId = String.Join("_", propertyNameParts.Skip(1));
string controlName = String.Join(".", propertyNameParts.Skip(1));
// get the value of the property
Func<TModel, int> compiled = expression.Compile();
int booleanSbyte = compiled(html.ViewData.Model);
// convert it to a boolean
bool isChecked = booleanSbyte == 1;
// build input element
TagBuilder checkbox = new TagBuilder("input");
checkbox.MergeAttribute("id", controlId);
checkbox.MergeAttribute("name", controlName);
checkbox.MergeAttribute("type", "checkbox");
checkbox.MergeAttribute("value", "0");
if (isChecked)
{
checkbox.MergeAttribute("checked", "checked");
checkbox.MergeAttribute("value", "1");
}
SetStyle(checkbox, htmlAttributes);
TagBuilder hidden = new TagBuilder("input");
hidden.MergeAttribute("name", controlName);
hidden.MergeAttribute("type", "hidden");
hidden.MergeAttribute("value", "0");
// script to handle changing selection
string script = "<script>" +
"$('#" + controlId + "').change(function() { " +
"if ($(this).is(':checked')) "+
"$(this).val('1'); " +
"else " +
"$(this).val('0'); " +
"}); " +
"</script>";
return MvcHtmlString.Create(checkbox.ToString(TagRenderMode.SelfClosing) + hidden.ToString(TagRenderMode.SelfClosing) + script);
}
private static void SetStyle(TagBuilder control, object htmlAttributes)
{
if(htmlAttributes == null)
return;
// get htmlAttributes
Type t = htmlAttributes.GetType();
PropertyInfo classInfo = t.GetProperty("class");
PropertyInfo styleInfo = t.GetProperty("style");
string cssClasses = classInfo?.GetValue(htmlAttributes)?.ToString();
string style = styleInfo?.GetValue(htmlAttributes)?.ToString();
if (!string.IsNullOrEmpty(style))
control.MergeAttribute("style", style);
if (!string.IsNullOrEmpty(cssClasses))
control.AddCssClass(cssClasses);
}