简体   繁体   English

将值从父视图传递给局部视图

[英]Pass a value to a partial view from parent view

I have a Web app where my controller passes a model to the parent view like so:我有一个 Web 应用程序,其中我的控制器将模型传递给父视图,如下所示:

 public ActionResult Results()
 {
     //Processing

     return View ("ParentView",model);
 }

Within my "ParentView" I will do render a partial view like so:在我的“ParentView”中,我将渲染一个局部视图,如下所示:

 @Html.Partial("_PartialView", anotherModel)

Now I would like to not touch the anotherModel at all.现在我根本不想碰anotherModel

But what I am trying to do is pass a value to _PartialView from the ParentView .但我想要做的是从ParentView_PartialView传递一个值。

I know I can pass something like ViewBag.Value="Text" from the Controller to the "ParentView" , however is something like that doable from "ParentView" to "_PartialView" ?我知道我可以将ViewBag.Value="Text"从 Controller 传递给"ParentView" ,但是从"ParentView""_PartialView"是否可行?

Basically I want to add a value in the model that is being used by "ParentView" , and somehow pass it down to "_PartialView"基本上我想在"ParentView"正在使用的model中添加一个值,并以某种方式将其传递给"_PartialView"

You can pass properties from your PageView Model to your PartialView like this:您可以将属性从PageView模型传递到PartialView如下所示:

@Html.Partial("_PartialView", @Model.AnotherModel)

You then set the Model of your _PartialView to be of the type of AnotherModel .然后,设置你的的型号_PartialView是类型的AnotherModel

You will have to create a View model.您必须创建一个视图模型。 you can create it by 3 ways您可以通过 3 种方式创建它

first way第一种方式

public class ViewModel
{
public class ParentViewModel {get; set;}
public class ChildViewModel {get; set;}
}

in this case your view在这种情况下,您的观点

@model ViewModel
 
    
...... //html is using @Model.ParentViewModel)

  @Html.Partial("_PartialView", @Model.ChildViewModel)

second way第二种方式

public class ParentViewModel:ChildViewModel

in this case the same model can be used for both在这种情况下,相同的模型可用于两者

@model ParentViewModel
 
    
...... //html is using @Model)

  @Html.Partial("_PartialView")

The third way can be used if it is possible to use interface to another model如果可以使用另一个模型的接口,则可以使用第三种方式

partial view局部视图

@model IAnotherModel

viewmodel视图模型

public class ViewModel:IAnotherModel

view is the same as the second way视图与第二种方式相同

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

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