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

734 views Asked by At

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.

2

There are 2 answers

0
David On BEST ANSWER

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.

1
SimonGoldstone On

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