无法从'lambda表达式'转换为'system.func动态对象'MVC3 Razor

时间:2014-04-29 13:59:25

标签: c# asp.net-mvc-3 razor webgrid

我收到了上述错误和"无效的参数"在我的视图页面中出现WebGrid.column错误。

//视图

@{
    WebGrid grid = new WebGrid(Model.LoadProductDetails());
     @grid.GetHtml(
         tableStyle: "grid",
         fillEmptyRows: false,
         headerStyle: "gvHeading",
         alternatingRowStyle: "gvAlternateRow",
         rowStyle: "gvRow",
         footerStyle: "gvFooter",
         mode: WebGridPagerModes.All,
         firstText: "<< First",
         previousText: "< Prev",
         nextText: "Next >",
         lastText: "Last >>",
         columns: new[] {
         grid.Column("ProductId",header: "ID"),
         grid.Column("ProductName",header: "Product"),
         grid.Column("Price"),
         grid.Column("Qunatity"),     
         grid.Column("ReorderLevel", header: "R.O.L."),
         grid.Column("ContactusId", header: "Action", canSort:false, format: @<text> @Html.Raw("<img src='/img/edit.png' title='Edit' onclick='EditProduct("+ item.ProductId  ")'  />") @Html.Raw("<img src='/img/delete.png' title='Delete' onclick='DeleteProduct("+ item.ProductId +")'  />") </text>)       
     })    
}

错误在格式附近的最后一列(ContactUsId)中抛出。我哪里错了?

请帮助。

1 个答案:

答案 0 :(得分:1)

从我的评论:看起来你试图将客户端HTML注入服务器端函数调用(这反过来会生成客户端输出)。这与MVC的工作原理相反(代码注入页面HTML)。你需要制作那些@&lt;&gt;进入C#字符串。然后它可以在服务器端处理,生成的GetHtml方法将最终结果注入输出。

示例:像这样的东西

@{
    string template = "<text><img src='/img/edit.png' title='Edit' onclick='EditProduct("+ item.ProductId + ")' /><img src='/img/delete.png' title='Delete' onclick='DeleteProduct("+ item.ProductId +")' /></text>";
    WebGrid grid = new WebGrid(Model.LoadProductDetails());
     @grid.GetHtml(
         tableStyle: "grid",
         fillEmptyRows: false,
         headerStyle: "gvHeading",
         alternatingRowStyle: "gvAlternateRow",
         rowStyle: "gvRow",
         footerStyle: "gvFooter",
         mode: WebGridPagerModes.All,
         firstText: "<< First",
         previousText: "< Prev",
         nextText: "Next >",
         lastText: "Last >>",
         columns: new[] {
         grid.Column("ProductId",header: "ID"),
         grid.Column("ProductName",header: "Product"),
         grid.Column("Price"),
         grid.Column("Qunatity"),     
         grid.Column("ReorderLevel", header: "R.O.L."),
         grid.Column("ContactusId", header: "Action", canSort:false, format: template)    
}

为任何拼写错误道歉,但这只是为了表明您应该做什么,而不是尝试使用Razor语法将HTML注入C#(这将无法工作)。

作为可读性改进,我会使用string.Format替换模板字符串中的标记。

e.g。

    string template = string.format("<text><img src='/img/edit.png' title='Edit' onclick='EditProduct({0})' /><img src='/img/delete.png' title='Delete' onclick='DeleteProduct({0})' /></text>", item.ProductId);