Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
.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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!