简单的问题真的。
我有一个显示一个可为空布尔,E,G MVC视图,
Html.CheckBoxFor(model=>model.NullableBoolHere, Model.NullableBoolHere,
我想创建一个新的HTML辅助,将接受这种类型的,然后转换
Null || False => False
True => True
所以,我有以下
public static MvcHtmlString CheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool?>> expression, object htmlAttributes, bool disabled)
{
IDictionary<string, object> values = new RouteValueDictionary(htmlAttributes);
if (disabled)
values.Add("disabled", "true");
Expression<Func<TModel, bool>> boolExpression = CONVERT_TO_BOOL_HERE(expression);
return htmlHelper.CheckBoxFor(expression, values);
}
任何帮助表示赞赏,我知道我将不得不使用递归复制的表达,但只是不知道如何去导航表达自己,找到?转换到bool的布尔。
您可以使用此代码:
var body = Expression.Coalesce(expression.Body, Expression.Constant(false));
var boolExpression = (Expression<Func<TModel, bool>>)
Expression.Lambda(body, expression.Parameters.First());
其他答案的优点是它不会编译第一个表达式,它只是包装它。 所产生的表达是相似于一个由该代码创建的:
m => m.NullableBoolHere ?? false
检查直播 。
所以,到最后,我能找到的唯一办法做到这一点是解决了布尔? 成布尔自己,然后通过传递正确的名称等返回一个“正常”的复选框
这样确实一种享受了,所以都好。 如果你知道得到正确的参数名称的一个更好的办法,这将是巨大的听到。
public static MvcHtmlString CheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool?>> expression, object htmlAttributes, bool disabled)
{
IDictionary<string, object> values = new RouteValueDictionary(htmlAttributes);
if (disabled)
values.Add("disabled", "true");
//Compile the expression to get the value from it.
var compiled = expression.Compile().Invoke(htmlHelper.ViewData.Model);
bool checkValue = compiled.HasValue ? compiled.Value : false; //evaluate the compiled expression
//Get the name of the id we should use
//var parameterName = ((MemberExpression)expression.Body).Member.Name; // only gives the last part
string parameterName = expression.Body.ToString().Replace("model.", "");//.Replace(".", HtmlHelper.IdAttributeDotReplacement);
//Return our 'hand made' checkbox
return htmlHelper.CheckBox(parameterName, checkValue, values);
}
我想这不会是不够的,只是表达转换为另一种类型,MVC使用表达式的一个原因,所以我怀疑它需要检查给定的表达和运用它的一些魔术。
您可以创建一个新的表达式执行转换,如下所示:
Expression<Func<TModel, bool>> boolExpression =
T => expression.Compile()(T).GetValueOrDefault(false);
但正如我所说,我怀疑这是不够的,MVC可能要检查表达式中的模型成员等。
这个怎么样:
Expression<Func<TModel, bool>> boolExpression = model =>
{
bool? result = expression.Compile()(model);
return result.HasValue ? result.Value : false;
};
这样,你的包装原始表达式,你可以将结果从布尔转换? 为bool。
它解决问题了吗?