我尝试使用以下代码在webgrid列中添加一个html图像:
@model List<LoUCore.Models.Artifact>
@{
var grid = new WebGrid(Model);
List<WebGridColumn> column = new List<WebGridColumn>();
column.Add(new WebGridColumn { ColumnName = "Filepath", Header = "Sprite",Format = (x => @<text><img src="@x.Filepath"></img></text>) });
}
@grid.GetHtml(columns: grid.Columns(column.ToArray()))
但我得到以下错误:
CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type
有什么想法吗?
答案 0 :(得分:3)
您不能在lambda表达式中使用嵌入式剃刀字符串,因为@Alessandro D'Andra建议您必须使用x => "<img src='" + someString + "'></img>";
。
你可能还需要将它全部包装在MvcHtmlString
中以防止Razor在格式化程序使用后转义字符串,但我不确切知道格式化程序是如何工作的 - 你必须尝试它
我制作了一个小测试文件,以确切了解Razor编译器将对您的代码执行的操作。这是剃刀文件:
@{
string someString = "somestring";
Func<object, object> a = x => "<text><img src='" + someString + "'></img></text>";
Func<object, object> b = x => @<text><img src="@someString"></img></text>);
}
ASP.NET编译器从中创建此C#代码(仅包含相关部分):
string someString = "somestring";
Func<object, object> a = x => "<text><img src='" + someString + "'></img></text>";
Func<object, object> b = x =>
#line default
#line hidden
item => new System.Web.WebPages.HelperResult(__razor_template_writer => {
BeginContext(__razor_template_writer, "~/Views/Home/Index.cshtml", 210, 4, true);
WriteLiteralTo(__razor_template_writer, "<img");
EndContext(__razor_template_writer, "~/Views/Home/Index.cshtml", 210, 4, true);
WriteAttributeTo(__razor_template_writer, "src", Tuple.Create(" src=\"", 214), Tuple.Create("\"", 231)
#line 7 "c:\temp\MvcApplication1\Views\Home\Index.cshtml"
, Tuple.Create(Tuple.Create("", 220), Tuple.Create<System.Object, System.Int32>(someString
#line default
#line hidden
, 220), false)
);
BeginContext(__razor_template_writer, "~/Views/Home/Index.cshtml", 232, 7, true);
WriteLiteralTo(__razor_template_writer, "></img>");
EndContext(__razor_template_writer, "~/Views/Home/Index.cshtml", 232, 7, true);
在lambda表达式中使用嵌入式文本语法@<text>
会产生明显不正确的C#代码。将嵌入式标签作为lambda表达式的一部分是不够智能的,而是通过插入代码立即发出嵌入文本来打破lambda表达式。
答案 1 :(得分:0)
一切皆有可能,试试这个:
@model List<LoUCore.Models.Artifact>
@{
var grid = new WebGrid(Model);
}
@grid.GetHtml(columns: grid.Columns(
grid.Column("Filepath", header: "Sprite", format: x =>
((Func<dynamic, object>)(@<text><img src="@x.Filepath"></img></text>)).Invoke(x)
)
))
或者更短:
@grid.GetHtml(columns: grid.Columns(
grid.Column("Filepath", header: "Sprite", format: @<img src="@item.Filepath"></img>)))