Home > Back-end >  Razor Pages with JQuery & DRY principle
Razor Pages with JQuery & DRY principle

Time:11-22

I'm writing a web app with ASP.NET Core, Entity Framework Core and Razor Pages. I have many pages that use jQuery to speak to the page controller: dropdown value from one selection may change another dropdown like this:

        $(function () {
            $("#Position_PositionState").on("change", function () {
                var projectId = $("#Position_ProjectId").val();
                $.getJSON(`?handler=Project&projectId=${projectId}`, function (response) {
                    if (response === "Inactive") {
                        var state = document.getElementById('Position_PositionState');
                        for (var i = 0; i < state.options.length; i  ) {
                            if (state.options[i].text === response) {
                                state.selectedIndex = i;
                                break;
                            }
                        }
                    }
                });
            });
        });

The code on the page that gives JSON responses looks like this:

        public async Task<JsonResult> OnGetProjectAsync(string projectId)
        {
            if (!string.IsNullOrWhiteSpace(projectId))
            {
                if (Int32.TryParse(projectId, out int id))
                {
                    var project = await _context.Projects.FindAsync(id);
                    if (project != null)
                    {
                        if (project.ProjectState == ProjectState.Active)
                            return new JsonResult("Active");
                        else
                            return new JsonResult("Inactive");
                    }
                    else return new JsonResult("Inactive");
                }
                else
                {
                    return new JsonResult("Inactive");
                }
            }
            return new JsonResult("Inactive");
        }

The questions are:

  • How to move the code repeated on many pages (Controller code) to a separate utility class and pass ApplicationContext to it.
  • How and where to instantiate that utility class.
  • How to call that utility class from jQuery.

I can only use this code on .cshtml.cs page that has the .cshtml view with jQuery, not in other places.
Thanks in advance for the help.

CodePudding user response:

you can reverse the code to decrease nesting

public async Task<JsonResult> OnGetProjectAsync(string projectId)
{
    if (!string.IsNullOrWhiteSpace(projectId) &&
                        Int32.TryParse(projectId, out int id))
    {
        var project = await _context.Projects.FindAsync(id);
        if (project != null && project.ProjectState == ProjectState.Active)
         return new JsonResult("Active");
    }
    return new JsonResult("Inactive");
}

CodePudding user response:

Not the answer, but your Action code could be simplified, there are too many returns and ifs.

An example:

public async Task<JsonResult> OnGetProjectAsync(string projectId)
{
    if (!int.TryParse(projectId, out int id))
    {
        return new JsonResult("Inactive");
    }
    var project = await _context.Projects.FindAsync(id);
    var result = project?.ProjectState == ProjectState.Active 
        ? "Active"
        : "Inactive";
    return new JsonResult(result);
}

Checking string.IsNullOrWhitespace is not needed because int.TryParse will return false is the ProjectId string is null or whitespace.

There is also no need to explicitly check if project is null because wa can propagate the null with the ? operator, and null == ProjectState.Active will always be false.

  • Related