Tuesday, September 11, 2018

Am I doing Razor Pages/jQuery/AJAX inefficiently?

Hi all,

So what I'm currently doing feels like I'm bypassing some of the strengths of Razor Pages like model binding, and it feels like it doesn't scale. I have tons of <table> and <select> elements that I need to filter, and for each of my entities I pretty much have to create a method that will produce html from the data I'm getting back from the server in my AJAX calls.

In my PageModel, I will have something like this:

public class IndexModel : PageModel { private readonly IndexService _indexService { get; set; } public IndexModel(IndexService indexService) { _indexService = indexService; } public async Task<ActionResult> OnGetLoadEntriesAsync(int id) { return new JsonResult(await _indexService.GetEntriesAsync(id); } } 

I will call this handler from jQuery like so:

$.getJSON('/Index?handler=LoadEntries&id=' + id, function(data){ var html = ''; html += "<table>"; html += "<tr>"; html += "<th>description</th>"; html += "</tr>"; for (var i = 0; i < data.length; i++){ html += "<tr>"; html += "<td>" + data[i].description +"</td>"; html += "</tr>"; } html += "</table>"; // return html or directly attach it to an element $("#ele").html(html); }); 

There's got to be a better way. I find myself being able to do really cool stuff, like conditionally adding columns based on which page my JS executes, however, I feel like I'm repeating myself by manually crafting the HTML. I think I am nearing 3-4k lines of JS in one of my projects.

Is there an easier way? Am I neglecting a fundamental aspect of razor pages that allows me to request data like I can with jQuery?

I find that I can do neat things with Razor when a page initially loads - but AJAX is crucial.

I've looked into Vue a little bit but I keep seeing the similarity to Razor.

Sorry for the wall of text.

TL;DR:

JS is great, but I feel like I'm not adhering to DRY as well as I could.

Am I doing Razor Pages/jQuery/AJAX inefficiently? Click here
  • Blogger Comment
  • Facebook Comment

0 comments:

Post a Comment

The webdev Team