简体   繁体   中英

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:

 public ActionResult Results()
 {
     //Processing

     return View ("ParentView",model);
 }

Within my "ParentView" I will do render a partial view like so:

 @Html.Partial("_PartialView", anotherModel)

Now I would like to not touch the anotherModel at all.

But what I am trying to do is pass a value to _PartialView from the ParentView .

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" ?

Basically I want to add a value in the model that is being used by "ParentView" , and somehow pass it down to "_PartialView"

You can pass properties from your PageView Model to your PartialView like this:

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

You then set the Model of your _PartialView to be of the type of AnotherModel .

You will have to create a View model. you can create it by 3 ways

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

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