Can I put JavaScript in partial views?

Im is working on a web application where the main page contains two parts: a constant block that is always displayed, and an information block made up of one of three partial views. Each of the partial views appears as a result of the AJAX request and is loaded only once (after this, the jquery provided switch windows). It works well, but Ive encountered one problem.

The html code for partial representations contains js functions that are also used in the constant block and in the information block. When the page loads, these functions can โ€œseeโ€ each other and they work, but they cannot find function declarations and warn me about it. I cannot solve the problem by transferring them to an external js file due to the razor syntax that can be found in their code.

What can i do with this?

Thank.

Update:

Finally, I decided to solve the problem separating my js code from the views. So the new question was how to include razor syntax in js files or what is an acceptable alternative. Popular Ive solutions use global variables, data attributes, and the ones I like best - RazorJS library by John Katsiotis.

http://djsolid.net/blog/razorjs---write-razor-inside-your-javascript-files

I hope that it will work stably and make Resharper happy.

Hurrah!

Update:

After 3 years, I remembered this question and decided to update it in accordance with my experience. In fact, now I would prefer not to use additional libraries for this. Especially if you are not the only member of the project team ... It is much better if you are provided with all your libraries, they are supported by the creator and the community and can be easily integrated into your IDE (for example, if you use special syntax), also all the guys from Your team should know how this works. So now I propose to do the following:

  • Keep all JS in separate files. Isolate it as much as possible. Provide it with an external API.
  • Call API functions from your views.
  • Pass all the URLs created by Razor, text messages, constants as a resource parameter.

For example:

js file:

$.api.someInitFunction = function(resources){ ... } 

View:

 <script> $.api.someInitFunction({ urls: { myAction: '@Url.Action("MyAction", "MyController")' }, messages: { error: '@errorMessage' }, consts: { myConst: @myIntConst } }); </script> 
+43
javascript asp.net-mvc razor partial-views
Jun 19 2018-12-12T00:
source share
4 answers

If Resharper warns you that this is not a big deal ^ _ ^

But if I were you, I would not put JavaScript in a partial view at all .

Since a partial view can be inserted on the same page many times, you will get problems with your Java scripts.

And for your case, if you cannot separate JavaScript from the JS file, then just create another PartialView and put these scripts in it and simply display it on the main page.

+26
Jun 19 '12 at 11:00
source share

If you want to write partial views that are encapsulated โ€œwidgetsโ€ that just work after you include them on the page, then embedding a script block inside a partial view is one clean way to wrap the markup and initialization of a script together in a partial view. For example, I might have a partial view called "_EventList", which I use on my site. If I put in two places on my main page, it should work, and I prefer not to write logic on my main page to initialize the widget.

If you will never use it more than once per page, itโ€™s easy. But if you can, then wrap the script so that it doesn't run twice. See below. For snippets, I mimic it by repeating a partial view twice in a piece of code for presentation, including a partial view twice on the main page.

My main page might look like this:

 <div id="left-nav"> @Html.Partial("_EventList") </div> <div id="body"> </div> <div id="right-nav"> @Html.Partial("_EventList") </div> 

Example:

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!-- Self-contained partial view containing widget --> <div id="widgetDiv" class="panel panel-default"> <div class="panel-heading">Event Dates</div> <div class="panel panel-group"> <ul class="widget"> <!-- These will load dynamically --> </ul> </div> <script> $(document).ready(function() { // Run this once only in case widget is on page more than once if(typeof $widget == 'undefined') { $widget = $("ul.widget"); // could be more than one // mock data to simulate an ajax call var data = [ {Description: "March", StartDate: "03/01/2015"}, {Description: "April", StartDate: "04/01/2015"}, {Description: "May", StartDate: "05/01/2015"} ]; $.each($widget, function(w, widget) { // might be an $.ajax call $.each(data, function(i, row) { $(widget).append("<li><a href='/Widget/Search?startDate=" + row.StartDate + "'>" + row.Description + "</a></li>"); }); }); } }); </script> </div> <!-- End of widget / partial view --> <!-- Second copy of above for sake of example snippet --> <!-- No need to read further --> <!-- Self-contained partial view containing widget --> <div id="widgetDiv" class="panel panel-default"> <div class="panel-heading">Event Dates</div> <div class="panel panel-group"> <ul class="tinylist nav nav-sidebar widget"> <!-- These will load dynamically --> </ul> </div> <script> $(document).ready(function() { // Run this once only in case widget is on page more than once if(typeof $widget == 'undefined') { $widget = $("ul.widget"); // could be more than one // mock data to simulate an ajax call var data = [ {Description: "March", StartDate: "03/01/2015"}, {Description: "April", StartDate: "04/01/2015"}, {Description: "May", StartDate: "05/01/2015"} ]; $.each($widget, function(w, widget) { // might be an $.ajax call $.each(data, function(i, row) { $(widget).append("<li><a href='/Widget/Search?startDate=" + row.StartDate + "'>" + row.Description + "</a></li>"); }); }); } }); </script> </div> <!-- End of widget / partial view --> 
+5
Apr 27 '15 at 21:26
source share

I agree with Wahid that you should not put JavaScript in your views on partial or otherwise. I have seen enough code that does this to know that it does not mean anything.

I would also say that you should be able to pass the logic encapsulated in Razor syntax into JavaScript, you just need to pass the information your logic needs to your JavaScript.

I just can guess from the experience of this next comment, but you should design JavaScript the same way you would when designing a C # or VB.NET code structure. Therefore, the logic you use Razor for should be part of your JavaScript.

That way, your JavaScript will be easier to maintain, and I believe Resharper should also be happier.

+3
Jun 19 '12 at 11:14
source share

I do this and find it very convenient. It works great to dynamically load partial javascript fragments with ViewBag, HttpContext, etc. available.

This leads to something that looks like using T4 templates.

You can even get javascript, intellisense, etc. validation if you add phantom script tags like this.

 @using System.Configuration @if (false) { @:<script type="text/javascript"> } $scope.clickCartItem = function(cartItem) { console.log(cartItem); window.location.href =@Html.Raw("('" + ConfigurationManager.AppSettings["baseUrl"] + "/Checkout/' + cartItem.ItemId)"); }; dataAccess.getCart( function (response) { //... }, function (response) { //... } ); @if (false) { @:</script> } 
+1
Sep 15 '14 at 8:09
source share



All Articles