What is the best way to adjust the priority of elements using JavaScript in an ASP.NET MVC application?

As part of my application, I need to create a function that allows for the changing of deputy priorities for each consultant. Here is what I have implemented so far:

View:

@model ML.Domain.DAL.DB_CONSULTANTS
....
<table>
    <tr>
        <th>ID Deputy</th>
        <th>Priority</th>
        <th></th>
        <th></th>
        <th></th>
    </tr>
    @foreach (var item in Model.DB_CONSULTANT_DEPUTY.OrderBy(x => x.PRIORITY))
    {
        <tr>
            <td>@item.DEPUTY_ID</td>
            <td>@item.PRIORITY</td>
            <td><button class="btn btn-default up" data-consultant-id="@item.CONSULTANT_ID" data-deputy-id="@item.DEPUTY_ID" data-priority="@item.PRIORITY">UP</button></td>
            <td><button class="btn btn-default down" data-consultant-id="@item.CONSULTANT_ID" data-deputy-id="@item.DEPUTY_ID" data-priority="@item.PRIORITY">DOWN</button></td>
            <td><button class="btn btn-default delete" data-consultant-id="@item.CONSULTANT_ID" data-deputy-id="@item.DEPUTY_ID" data-priority="@item.PRIORITY">Remove</button></td>
        </tr>
    }
</table>

Script (currently only for removing deputy):

<script>
    var url = '@Url.Action("RemoveDeputy", "Consultant")';
    $('.delete').click(function () {
        var container = $(this).closest('tr');
        var data = { consultant_Id: $(this).data('consultant-id'), deputy_Id: $(this).data('deputy-id'), priority: $(this).data('priority') };
        $.post(url, data, function (response) {
            if (response)
            {
                // fadeout, then remove
                container.fadeOut(800, function () {
                    $(this).remove();
                });
            } else
            {
                alert("Error!");
            }
        }).fail(function () {
            alert("Error!");
        });
    });
</script>

Backend:

[HttpPost]
public JsonResult RemoveDeputy(DB_CONSULTANT_DEPUTY model)
{
    consultantRepository.RemoveDeputy(model);
    return Json(true);
}

I also need to add a similar function to the script, where if a user clicks on the UP or DOWN button, the same data as for DELETE will be sent to the backend and the priority will be changed accordingly. For example:

[HttpPost]
public JsonResult ChangePriorityToUp(DB_CONSULTANT_DEPUTY model)
{
    var deputyForChangePriority = db.DB_CONSULTANT_DEPUTY.Find(model.DEPUTY_ID);
    deputyForChangePriority.PRIORITY -= 1;

    if (db.DB_CONSULTANT_DEPUTY.Any(x => x.PRIORITY == deputyForChangePriority.PRIORITY + 1)) 
    {
        var deputyToRefresh = db.DB_CONSULTANT_DEPUTY.First(x => x.PRIORITY == deputyForChangePriority.PRIORITY + 1);
        deputyToRefresh.PRIORITY -= 1;
    }
    db.SaveChanges();
    return Json(true);
}

Lastly, I need to figure out how to refresh the table view after these changes are made using JavaScript functions. Any help with this part would be greatly appreciated.

Answer №1

To modify the POST method to allow changing the PRIORITY in either direction, follow these steps:

[HttpPost]
public JsonResult UpdatePriority(int deputyId, int priority)
{
    var model = db.DB_CONSULTANT_DEPUTY.Find(deputyID);
    if (model != null)
    {
        model.PRIORITY = priority;
        db.SaveChanges();
        return Json(true);
    }
    return Json(null);
}

Next, update the HTML code:

@foreach (var item in Model.DB_CONSULTANT_DEPUTY.OrderBy(x => x.PRIORITY))
{
    <tr data-consultant-id="@item.CONSULTANT_ID" data-deputy-id="@item.DEPUTY_ID" data-priority="@item.PRIORITY">
        <td>@item.DEPUTY_ID</td>
        <td>@item.PRIORITY</td>
        <td><button class="btn btn-default up">UP</button></td>
        <td><button class="btn btn-default down">DOWN</button></td>
        <td><button class="btn btn-default delete">Remove</button></td>
    </tr>
}

Lastly, add the following script:

var priorityUrl = '@Url.Action("UpdatePriority", "Consultant")';
$('.up, .down').click(function() {
    var row = $(this).closest('tr');
    var deputyId: row.data('deputy-id')
    var priority = row.data('priority')
    if($(this).hasClass('up')) {
        priority++;
    } else {
        priority--;
    }
    $.post(url, { deputyId: deputyId, priority: priority }, function(response) {
        if(response) {
            row.children('td').eq(1).text(priority);
            row.data('priority', priority);
        } else {
            // Oops
        }
    }).fail(function () {
        // Oops
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing webpack to import both d3 and d3-cloud libraries

I've been attempting to integrate d3 and d3-cloud (for word cloud) into my AngularJs(v - 1.4) app by using: import d3 from 'd3' import d3Cloud from 'd3-cloud'. However, when trying to use d3-cloud with d3.layout.cloud(), ...

To insert a <div> element within a <tr> element while preserving the exact position of the <tr> tag - here's how you can do it:

I have a challenge with my table where I need to add a green progress bar in the form of a div element within a tr. The width of this progress bar should change dynamically from 0% to 100%, reflecting the current runtime of the video associated with that p ...

What is the best way to implement function chaining in TypeScript?

I'm interested in implementing function chaining in typescript. Let's consider a sample class: export class NumberOperator { private num; constructor(initialNum) { this.num = initialNum; } public add(inc = 1) { this.num += inc ...

Can JSF Ajax be used to update non-JSF components like plain HTML elements?

Is it feasible to make changes to sections of my webpage that are not JSF elements? For instance, can I modify a simple HTML <div> or should I enclose it in a JSF component? ...

Traverse an array containing nested objects using Javascript

I am facing difficulty printing out objects stored in an array. When I console log, this is the result: console.log(product.categories) https://i.stack.imgur.com/YVprQ.png How can I iterate through these nested objects to display them individually like t ...

Is there a way to remove the bold styling from text next to JavaScript?

I recently launched a website at www.mvscaccounting.com, and I added a search engine made from javascript at the bottom of the page. Next to it, I wanted to put a "all rights reserved" notice. However, whenever I try to add any text next to the search engi ...

Arrange search results within a Session based on a specific parameter

Is there a way to sort search results stored in a Session named Session("ListSearchResults") by age? The session contains information about various individuals such as their name, town, and age. I attempted the following code snippet but it did not produc ...

What steps do I need to follow to create a 3D shooting game using HTML5 Canvas?

I'm eager to create a 3D shooter game with HTML5 Canvas, focusing solely on shooting mechanics without any movement. Can anyone provide guidance on how to accomplish this? I've looked for tutorials online, but haven't come across any that m ...

The functionality of the ui sortable feature in Angular is not effective when used on a single-page website

My latest project involves using a single-page application. To connect the UI Angular library, I followed these steps: I started by adding the necessary scripts: <script src=.....jquery-1.9.1.js"></script> <script src=.....jquery-ui.js"> ...

Utilizing titanium to develop a functionality that listens for button presses on any area of the screen

I am trying to simplify the action listener for 9 buttons on a screen. Currently, I have individual event handlers set up for each button, which seems inefficient. Is there a way to create an array of buttons and manipulate them collectively? For example ...

Utilizing Shadow Root and Native Web Components for Seamless In-Page Linking

An illustration of this issue is the <foot-note> custom web component that was developed for my new website, fanaro.io. Normally, in-page linking involves assigning an id to a specific element and then using an <a> with href="#id_name&quo ...

Enhancing ASP.NET with jQuery for Efficient Ajax Requests

I have a textBox that uses jQuery to trigger an ajax request: <asp:TextBox ID="postcodeTextBox" runat="server" Text='<%# Bind("POSTAL_ZIP_CODE") %>'> $(document).ready(PageLoad); function PageLoad() { $(container + 'parent ...

Tips for ensuring proper dependency regulations in javascript/typescript/webpack

In essence, I am in search of a method to limit dependencies, similar to how one would manage different projects (libraries) in Java or C#. Think of it as friend or internal access modifiers. I'm considering various approaches to accomplish this (suc ...

The ever-changing world of list items with dynamic editions

One of my tasks involves displaying a list of elements through the ng-repeat directive. Each element is contained within its own div block. My goal now is to enable editing for each block, so that when users click on an edit button, the content of the div ...

Discover the unseen: The ultimate guide to detecting visible objects in a (deferLoad) event

I'm utilizing the (deferLoad) method to load an image gallery in a more controlled manner. Is there any event available that can inform me about which items are currently visible? The main goal is to load a set of data along with an image path, and t ...

Using JavaScriptSerializer in MVC to deserialize JSON data

Here is the jQuery code snippet I am using: var items = new Array(); items.push({ "Item1":$("myvalue").val(), "Item2":$("myvalue2").val() }); .... data: { 'items': JSON.stringify(items) }, .... I ...

button to dim the image collection

On the top right corner of my image gallery, there's a button that, when clicked, creates an overlay darkening the image. I'm trying to figure out how to toggle this effect on and off with a click. Any suggestions on how I can achieve this? Here ...

Pause for a brief moment before proceeding to the next task within the map

My situation involves having a list of usernames that represent accounts: let users = [ "user1","user2","user3","user4","user5","user6","user7" ] users.map(async (user, i) => { co ...

Organizing elements in a javascript array by their attributes using AngularJS

Picture this scenario: a collection of different wines: [ { "name":"wine A", "category":[ "red", "merlot" ] }, { "name":"wine B", "category":[ "white", "chardonnay" ...

Managing configuration variables in ExpressJS for various environments

Is it possible to set a variable for different environments when defining the environment? app.configure 'development', () -> app.use express.errorHandler({dumpExceptions: true, showStack: true}) mongoose.connect 'mongodb://xxx:<a h ...