'.NET MVC - Enabling script sections for AJAX-returned partial views
I would like to make use of the (script) section in ASP .NET MVCs, i.e :
@section script
{
<script>alert("hello");</script>
}
...but with partials views as well, regardless of wether they are used within a complete page or an AJAX-returned content.
It seems like MVC is expecting me to return partial views directly when doing AJAX, by returning a PartialViewResult
. But if I do this, the returned view does not have a parent layout, which is where the @RenderSection insctruction is supposed to be, which causes the scripts declared in the script sections not to be rendered.
(By the way it's not a question about whether returning scripts through AJAX is correct, that's another subject)
To fix this issue, I thought about adding the @RenderSection
instruction in the partial view. But this would not work, because the partial view is not guaranteed to be the root view of the return content, but also because it would make a duplicated call to @RenderSection
, were the partial used in a complete page.
So my second solution is to use an "empty" layout for every AJAX calls that is supposed to return HTML content, with only two instructions in that layout : @RenderBody
to render the partial view tree, and @RenderSection
to render all the scripts declared in script sections within the partial views.
This second solution seems to perfectly suit my needs. However, it seems like this is not doing AJAX the way MVC is expecting me to, so I am worried this idea causing me problems in the future that I can't foresee at this day.
Would you care to give me your opinion on this ?
Thank you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|