David
David

Reputation: 16120

How to pass data from child action to layout in ASP.NET MVC

I have a view which uses a layout, and also executes a child action.

The layout calls a partial which needs some data from the view's child action. Is there some way to pass the data up from the child action to it's parent view's layout?

I have tried solving this using sections, but it appears that sections can only be rendered in layout views.

Upvotes: 2

Views: 759

Answers (2)

David
David

Reputation: 16120

In the end, I had the child action stuff the required data into the HttpContext. This was then read out by the view containing the child action, which used it to render a section in the layout.

I was concerned that the order of processing of the views would not be predictable (i.e. that I couldn't be sure that the data would be written to the HttpContext before being read from it), but it turns out the order of processing is entirely predictable.

Upvotes: 2

SimonGoldstone
SimonGoldstone

Reputation: 5216

In your child action, you can set up the data as data-*** attributes and then use JavaScript (or jQuery) to read them back in your partial.

E.g. child action:

<div id="somedata" data-customerid="123" data-reference="xyz">
</div>

Then in your partial:

<script> 
   ....
   var customerId = $("#somedata").data("customerid");
   var reference = $("#somedata").data("reference");
</script>

Hope this helps

Upvotes: 0

Related Questions