lambda函数是否可以包含Razor语法并在View中执行? [英] Is it possible for a lambda function to contain Razor syntax and be executed in a View?

查看:53
本文介绍了lambda函数是否可以包含Razor语法并在View中执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用Razor语法定义lambda表达式(委托,Action,Func <>)的内容,以便在视图中执行此模型方法时,将插入该Razor内容?

Is it possible to define the contents of a lambda expression (delegate, Action, Func<>) with Razor syntax, so that when this model method is executed in the view, it will insert that Razor content?

此操作的预期目的是使我们的开发人员能够定义自己的自定义内容,以将其插入到CustomControl视图的特定位置.

The intended purpose of this is for our developers to be able to define their own custom content to be inserted at a particular point in the CustomControl's view.

以下是模拟我当前布局的简化示例代码.重点包括 RenderSideContent 方法定义及其执行调用.

The following is stripped-down example code that mimics my current layout. The particular parts of focus are the RenderSideContent method definition and its executing call.

Index.cshtml

Index.cshtml

@model My.PageModel

@My.CustomControl(new CustomControlModel
    {
        AreaTitle = "Details",
        RenderSideContent = () =>
        {
            <div>
                @using (My.CustomWrapper("General"))
                {
                    My.BasicControl(Model.Controls[0])
                }
            </div>
        }
    })

CustomControl.cshtml

CustomControl.cshtml

<div>
    @Model.AreaTitle
    <div class="my-custom-content">
        @Model.RenderSideContent()
    </div>
</div>

推荐答案

是,不是.不,您不能像这样给它提供自定义Razor,因为在这种情况下,您正在处理直接的C#,而<div>之类的东西不是有效的C#.但是,您可以 在lambda中构建IHtmlStringMvcHtmlString对象,然后返回那个.

Yes and no. No, you can't just feed it custom Razor like that, because in that context, you're dealing with straight C# and something like <div> is not valid C#. However, you can build an IHtmlString or MvcHtmlString object in the lambda and then return that.

但是,您将需要创建自定义控件的版本,这些版本分别返回 HTML和 render HTML.基本上,请考虑Html.PartialHtml.RenderPartial.前者实际上是写响应,而后者只是返回一个MvcHtmlString,可以随意渲染到页面上.

However, you're going to need to create versions of your custom controls that return HTML versus render HTML. Basically, think of Html.Partial vs Html.RenderPartial. The former actually writes to the response while the latter merely returns an MvcHtmlString that can be rendered to the page at will.

这篇关于lambda函数是否可以包含Razor语法并在View中执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆