4

I have a WebGrid in my Razor View. It's performing its task well like paging and sorting. Now I need to make the paging and sorting in ajax call, so I assigned it an ajaxUpdateContainerId.

Now When grid.GetHtml() method is called, it's rendering its script first and then the table Html. I have the jquery loaded at the end of the page(Script Section in _Layout view).

Due to this, Ajax functions are useless as it can't find JQuery.

I have a workaround for this: I copy the rendered script from page source and paste it in the script section of the view and it works but this still leaves the error in the console so I believe it's not a proper solution.

Another workaround is to reference jquery before calling grid.GetHtml() method but that will leave two references to the same javascript library. Again bad design.

So is there any way we can force WebGrid to render the script in script section as it should logically behave.

Anup Sharma
  • 2,053
  • 20
  • 30
  • When you declare the libraries and script references within your main page (the one that houses your partial views) your grid should be able to access the jquery within it without problems. Try moving the jquery from the @script section to the header of the page to see if your gridview will then see the jquery. – Dennis VW May 12 '17 at 14:43
  • @Dennis1679 Yes, you are right that Jquery can be moved to the head section. This will solve the problem with some performance hit. – Anup Sharma May 12 '17 at 15:56

2 Answers2

2
  1. Create your WebGrid in a partial view
  2. On doc $(document).ready(function () call in your main page, issue an ajax call to your controller to load up your model for your webgrid then pass the partial view back to load on your main page.

Here is an example where someone is doing something very similar. I followed this method when I ran into similar circumstances with a different control. http://www.dotnetawesome.com/2014/11/how-to-implement-custom-paging-and-sorting-in-webgrid-using-jquery.html

Travis Acton
  • 4,292
  • 2
  • 18
  • 30
1

you can define a section inside your view containing your script and render it after jquery is loaded

in your View (Containing the grid)

@section scripts{

<script>
//My awesome Script
</script>
}

and in you view /Layout

@RenderSection("scripts",required:false)

you can check this for more info

https://weblogs.asp.net/scottgu/asp-net-mvc-3-layouts-and-sections-with-razor

Hasan Elsherbiny
  • 598
  • 2
  • 14
  • 31
  • You didn't get my point. I don't have any issue with Razor Sections. The Problem is with the WebGrid ajax implementation. WebGrid is defining its script within its own scope. I need it to render *its* script in script section so that it works as defined in the question. – Anup Sharma May 08 '17 at 15:45