Asp.net-mvc – Render scripts for use in Partial View

asp.net-mvcscriptingviews

I've seen numerous sources stating that it's incorrect / bad practice to put scripts in Partial Views, but this raises a huge question…

How are you supposed to run scripts that interact with Partial Views? I've tried using @section scripts { } or something like that, but it doesn't work. At all. The section contains the scripts just fine, but they don't get rendered when the Partial is loaded into the full View.

In addition, I can't render the scripts my Partial View needs on my full View because the scripts pull values from the Model, which is only rendered on the Partial View, since it's the piece of the puzzle that actually works with data.

I hope that doesn't sound too complicated… How can I effectively, efficiently, and correctly render scripts for use with my Partial View's elements and Model?

Best Answer

@keyCrumbs I will not give you a direct answer, but something for you to analyze.
One of the most biggest problems in you call scripts for you partial view is replication of code.

Think you'll use ajax to get the partial view and you will continue doing this for a while. In every call you'll download the script code, and you put it in html. Every time you reset the script block in html, the functions are reset, the variables are reset. It's can be a big problem depending on your js code.

Other point is the size of the response, you can say, but js has a small size, and I'll say multiply this size for every call of a user and next multiply for ever user connected.

So finally, a solution for you, in this case is: create function in the page and call the function in partial view like this:

Your page: Page.cshtml

<script type="text/javascript">
    function myPartialView_Load() {
        $("birth").datepicker();
        $("phone").mask("000-0000");
    }
</script>

<!-- Some other code here -->

<div>
    <!-- Or you can call from a ajax or other way... -->
    @Html.Action("MyActionPartialView")
</div>

Your partial view: MyPartialView.cshtml

<script type="text/javascript">
    $(function () { myPartialView_Load(); });
</script>

<form>
    <input type="text" name="birth" id="birth" />
    <input type="text" name="phone" id="phone" />
</form>

So as you see the problem lies not in putting js in partial view, but the way as you do it. All rules of good practice has a "why" behind, if you understand the "why" you can determine how far the rule is a help and not a burden. And decide break it or not.

Like a said, I'm not given you a ultimate answer but something you thing about. You can use other ways to contour the problem.