简体   繁体   English

是否可以将部分视图中的特定内容渲染到主视图中?

[英]Is it possible to render specific content from Partial View into main view?

I have a partial view let say _ABCPartialView and within my partial view I have two <div> tags as below: 我有一个局部视图,可以说_ABCPartialView ,在局部视图中,我有两个<div>标记,如下所示:

<div>
//some dynamic stuff
</div>

<div>
<img src="blah blah"/>
</div>

Is it possible to render only the second <div> which contains an <img> tag into my main view? 是否可以仅将包含<img>标签的第二个<div>渲染到我的主视图中? This method @html.Partial("_ABCPartialView") renders all the elements of partial view. 该方法@html.Partial("_ABCPartialView")呈现部分视图的所有元素。 Your thoughts? 你的意见?

You can use the ViewData to provide arguments to your PartialView. 您可以使用ViewData为PartialView提供参数。 For Sample: 样品:

@Html.Partial("_ABCPartialView", null, new ViewDataDictionary { { "ShowSecondDiv", true } })

And inside your PartialView, you just use: 在PartialView中,您只需使用:

<div>

<div>

@if ((bool)ViewData["ShowSecondDiv"])
{
    <div>

    </div>
}

You can pass a model into your partial which will have a property whether to do that or not. 您可以将模型传递到局部模型中,该模型将具有是否执行此操作的属性。 For example: 例如:

This is the model: 这是模型:

public class YourModel 
{
    public bool ShowDiv { get; set; }
}

This is code in your parent view and it passes the info to your partial view: 这是父视图中的代码,它将信息传递到局部视图:

@Html.Partial("_ABCPartialView", new YourModel { ShowDiv = false });

Inside your partial view check that property and do what you need to do. 在局部视图中,检查该属性并执行所需的操作。

@if ((bool)Model.ShowDiv)
{
    <div>
         //some dynamic stuff
    </div>
}

A partial view can have a model just like a regular view. 局部视图可以像常规视图一样具有模型。 Also, with a model you get compiler help and intellisence so you do not have to worry about misspellings. 此外,使用模型,您可以获得编译器的帮助和智能,因此您不必担心拼写错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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