简体   繁体   中英

MVC 5 ASP.Net Razor Cannot convert lambda expression to type 'MvcHtmlString' because it is not a delegate type

I have this problem on inserting some html into a Lambda expression in an HtmlHelper. When I am trying to mix a lambda expression with some html.

HtmlCell<EmployeeViewModel>.Create(x=> new MvcHtmlString(@<div>@x.Email</div>), null) I get a error message on the @x.Email saying:

-Cannot convert lambda expression to type 'MvcHtmlString' because it is not a delegate type.

-Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type

The prototype of my HtmlHelper is :

public ICell<TModel> Create(Expression<Func<TModel, string>> html, object htmlAttributes = null)

I read this post in the past : https://stackoverflow.com/a/18291265/3114267 (but the answer is from 2014 so maybe it evolved)

Do you have any idea what is wrong? how can I fix it and how can I mix up a lambda and some "Html"?

Try this

HtmlCell<EmployeeViewModel>.Create(x=> 
    new MvcHtmlString(String.Format("<div>{0}</div>", x.Email)), null)

Update

if you want to avoid String.Format or html more complex then use @helper:

HtmlCell<EmployeeViewModel>.Create(x=> func(x).ToHtmlString()), null)

below in view

@helper func(EmployeeViewModel employeeViewModel )
{
    <div>@employeeViewModel.Email</div>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM