ASP中等效的多个ITemplate占位符.Net MVC



我是ASP的新手。NetMVC,并且一直使用Web窗体。我在MVC中找到了ITemplate的替换?其给出了创建名为BeginBlock的HTML帮助程序的示例,该HTML帮助程序包装标题&内容来自:

@using (Html.BeginBlock("MY TITLE")) {
MY CONTENT GOES HERE
}

<div>
<div><h1>MY TITLE</h1></div>
</div>
MY CONTENT GOES HERE

我有一个场景,在Web窗体中,我们曾经使用多个ITemplate来定义用户控件中的容器,然后将这些容器封装在HTML中。例如,在Web Forms中,我们可以创建一个名为Panel的用户控件,并具有两个ITtemplate属性,一个名称为Content,另一个名称是ContentNonScrollable。然后,我们将使用以下标记来使用用户控件:

<MySite:Panel>
<Content>
Content 1 Goes Here
</Content>
<ContentNonScrollable>
Content 2 goes here
</ContentNonScrollable>
</MySite:Panel>

然后,用户控件将输出以下HTML:

<div class="my-panel">
<div class="my-panel-content">
Content 1 Goes Here
</div>
<div class="my-scrollable-panel-content">
Content 2 Goes Here
</div>
</div>

在MVC中,有没有任何方法可以通过HTML Helpers(或其他任何东西),通过.cshtml模板文件中的标记,设计出与上面的Web窗体示例等效的东西?

例如(显然,下面没有正确的语法,只是为了解释我们的想法):

@using (Html.BeginPanel() {
{
Content 1 Goes Here
}
{
Content 2 Goes Here
}
}

您可以为此使用部分。分区是为布局(即母版页)设计的,但您可以嵌套母版页来创建分区。

但是,听起来你想把它作为某种类型的控件来做。另一个选择可能是模板剃刀代表

另一个选项是编辑器/显示模板,尽管这通常不仅仅是标记。您将使用变量来传递内容。

另一种选择是只使用Partial View,并使用ViewData传入上下文部分。

实际上,你可以用很多不同的方式来实现这一点,你选择哪种方式取决于你的需求。你能解释一下具体情况吗?

我不明白为什么不。我自己还没有尝试过,但既然你可以在.cshtml页面中混合标记和脚本,你应该能够做一些类似的事情

@using (Html.BeginPanel()) { 
@using(Html.BeginScrollableContent()) {
Content 1 goes here
}
@using (Html.BeginNonScrollableContent()) {
Content 2 goes here
}
}

我看了你提到的帖子(一个很好的帖子,BTW),你应该能够在实现过程中遵循这个例子。

感谢@mystere指导我走向模板化委托和部分视图,这些视图采用带有变量的模型,接受带有html标记的字符串,我找到了以下解决方法,这与我在上述场景中想到的方法相当。

创建一个名为_PanelPartial.cshtml的局部视图,并将模型设置为_PanelPartialModel类型,其中包含以下属性:

public class _PanelPartialModel
{
public Func<dynamic, HelperResult> Content { get; set; }
public Func<dynamic, HelperResult> NonScrollableContent { get; set; }
}

_PanelPartial.cshtml中,您可以拥有以下内容:

@model _PanelPartialModel
<div class="my-testing-panel">
<p>hello this is heading text</p>
<div class="my-testing-panel-content">
@Model.Content(null)
</div>
<p>And this is something in between madafuker!</p>
<div class="my-testing-panel-scrollable-content">
@Model.NonScrollableContent(null)
</div>
<p>and what about another footer!</p>
</div>

@模型。Content(null)和@Model。NonScrollableContent(null)是对模型中的委托变量的调用。这些服务器作为占位符。

然后,每当你需要使用这个面板时,你可以使用这样的东西:

@Html.Partial("_PanelPartial", new _PanelPartialModel() {
Content = @<text>
<div>This is the scrollable content</div>
</text>, 
NonScrollableContent = @<text>
<h2>This is non scrollable content</h2>
</text>
});

这最终会生成以下HTML标记:

<div class="my-testing-panel">
<p>hello this is heading text</p>
<div class="my-testing-panel-content">
<div>This is the scrollable content</div>
</div>
<p>And this is something in between madafuker!</p>
<div class="my-testing-panel-scrollable-content">
<h2>This is non scrollable content</h2>
</div>
<p>and what about another footer!</p>
</div>

最新更新