我试图创建一个lambda表达式,通过我的MVC帮助扩展来传递给视图。
我尝试过的与此类似:
Expression<Func<DoubleNumber,DoubleNumber>> expr2 = (DoubleNumber g) => g.Num1;
默认表达式是这样传递的:
public static MvcHtmlString DoubleBoxFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
//int id,
Expression<Func<TModel, TProperty>> expression)
{
...
Model类
public class DoubleNumber
{
public int Num1 { get; set; } // tried strings but again they are null
public int Num2 { get; set; }
}
使用正确的表达格式后,仍然无法使用它: 格式正确:
Expression<Func<DoubleNumber,int>> expr2 = (DoubleNumber g) => g.Num1;
在评论中提到。
错误:
"the type arguments cannot be inferred from the usage. try specifying the type arguments explicitly."
感谢您的帮助。 编辑2 - 改革
守则得到证实:
public static class DoubleBoxHelper
{
public static MvcHtmlString DoubleBoxFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
//int id,
Expression<Func<TModel, TProperty>> expression)
{
var builder = new StringBuilder();
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var model = metadata.Model as DoubleNumber;
var name = ExpressionHelper.GetExpressionText(expression);
var fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
var fieldId = TagBuilder.CreateSanitizedId(fullName);
// I'm going to use something like this instead of "expression" which seems because of the format or parameter or anything else it's producing an error which I mentioned,
Expression<Func<DoubleNumber,int>> expr2 = (DoubleNumber g) => g.Num1;
//The line which will cause the error happened
builder.AppendLine(htmlHelper.TextBoxFor(expr2 , new {class, etc} )
...
}
我还尝试了一些其他形式的TextBoxFor,如TextBoxFor或尝试制作 表达&GT;每个都会有一些内在的问题,并且仍在寻找一个简洁的解决方案。
由于
答案 0 :(得分:2)
我似乎无法重复你的问题,这似乎编译得很好;
public static class DoubleBoxHelper
{
public static MvcHtmlString DoubleBoxFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression)
{
var builder = new StringBuilder();
builder.AppendLine(htmlHelper.TextBoxFor(expression, new {bop = 1}).ToHtmlString());
return null;
}
internal class Program
{
private static void Main(string[] args)
{
HtmlHelper<DoubleNumber> helper = ...
helper.DoubleBoxFor(g => g.Num1);
}
}
}
我在代码中看到的唯一问题是您的表达式是硬编码为特定类型,而HtmlHelper
是通用的。由于可以使用任何类型的HtmlHelper
调用该方法,并且通用参数需要在表达式和帮助程序之间进行匹配,因此编译器不会让您编译代码。如果您采用硬编码HtmlHelper<DoubleNumber>
或者上面的代码采用具有匹配通用参数的表达式,那么编译得很好。
编辑:如果你想在帮助者中构建表达式,你根本不需要它是通用的;
public static MvcHtmlString DoubleBoxFor(this HtmlHelper<DoubleNumber> htmlHelper)
{
var builder = new StringBuilder();
builder.AppendLine(htmlHelper.TextBoxFor(g => g.Num1, new { bop = 1 }).ToHtmlString());
builder.AppendLine(htmlHelper.TextBoxFor(g => g.Num2, new { bop = 1 }).ToHtmlString());
return null;
}