transferring data from JavaScript to AJAX in MVC4

I am facing an issue where I need to select a value from a grid and pass it to ajax, but I keep getting an error saying "Id undefined". Can anyone help me find a solution for this problem? The goal is to delete records that are presented in the grid. Upon clicking the button, the selected value should be passed to an ajax function for the deletion process. While the value is successfully moved to ajax, the error occurs stating that 'policyid' is undefined. Thank you in advance for any assistance.

Code snippet for the grid column:

@{
    var grid = new WebGrid(Model.Policy, rowsPerPage: 20, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridcal");
              grid.Pager(WebGridPagerModes.NextPrevious);}
    @grid.GetHtml(
    tableStyle: "webgrid-table",
    headerStyle: "webgrid-header",
    footerStyle: "webgrid-footer",
    alternatingRowStyle: "webgrid-alternating-row",
    selectedRowStyle: "webgrid-selected-row",
    rowStyle: "webgrid-row-style",
    columns:
        grid.Columns(
        grid.Column("PolicyName","Policy Name",style: "colWidth"),
        grid.Column("PolicyValue","Policy Value",style: "colWidth"),
       // grid.Column ("Delete",format:@<text><a href="@Url.Action("DeletePolicy","Roles",new{PolicyId=item.PolicyId.ToString()})"><img src="~/Images/img-delete-blk-icon.png" width="9" height="9" alt="Delete"/></a> </text>)
        ****grid.Column(format: @<text><input type="image"  onclick="AJAXCall_Fun_DeletePolicy()" src="~/Images/img-delete-blk-icon.png" name="image" width="9" height="9" /></text>)****


            ))

             @if (grid.HasSelection)
                    {

                        <b>Policy Name</b>@AppliedPolicies.PolicyName<br />
                        <b>Policy Value</b>@AppliedPolicies.PolicyValue<br />

                    }

Ajax function:

function AJAXCall_Fun_DeletePolicy() {

    if ($.xhrPool.length > 0) {
        $.each($.xhrPool, function (idx, jqXHR) {
            if (jqXHR) {
                this.abort();
            }
        });
        $.xhrPool = [];
    }


  var PolicyId = getPolicyId();
    if (PolicyId.length > 0) {
        $.ajax({

            type: "GET",
            url: "/Roles/DeletePolicy",
            data: { 'PolicyId': JSON.stringify(PolicyId) },
            async: true,
            cache: false,
            datatype: "json",

Controller code snippet:

    public JsonResult DeletePolicy(string PolicyId)
    {
        bool status = false;
        using (clsBLLGroups objclsBLLGroups = new clsBLLGroups())
        {
            status = objclsBLLGroups.DeletePolicy(UserCookieWrapper.UserAccessToken, PolicyId.ToString());


        }
        return Json(status, JsonRequestBehavior.AllowGet);
    }

Answer №1

To display a web grid in the form of a table, refer to this resource on how to get the id of a selected row in an HTML table. You can then pass this id through your ajax call to the controller. You mentioned PolicyId is part of the controller code. If you need to include a value from your model in the ajax call, just use @

var PolicyId = '@(Model.PolicyId)';

This value can also be used in your url. We typically use

url: '@Url.Action("DeletePolicy", "Roles")',

as our url structure. I hope this explanation helps

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

Is it feasible to send props to { children } within a React functional component?

Workaround presented below. I am attempting to send props down to a child component using {children}. The Parent component: const ParentComp = ({ children, propsToSendToChild }) => ( <div>Dynamic component content: {children} &l ...

Including a personalized User-Agent string in my headers for fetch requests

Currently, I am utilizing the fetch API within my React project to retrieve data from a JSON endpoint. One requirement I have is to include a custom User-Agent string in my requests. Upon inspecting my requests, I noticed that the UA string displays as: ...

What is the best way to send props to a component that is exported using a Store Provider?

I'm trying to export my react component along with the redux store Provider. In order to achieve this, I've wrapped the component with an exportWithState callback. However, I'm facing an issue where I can't seem to access the props that ...

Having trouble fetching results from AJAX objects using vanilla JavaScript?

I am currently working on developing my own AJAX prototype without relying on jQuery or any other libraries. However, I am facing an issue where I cannot retrieve any results and the breakpoint set on a specific line is not triggering: The problem seems t ...

I am encountering an issue where my Vue navbar is successfully changing the route but not updating the corresponding router-view

I have been working on a single-page application using Vue and I encountered an issue with the navbar when navigating through routes. The problem is that after the first click on a navbar item, the route changes successfully but the router-view does not up ...

looping through the multi-dimensional array using v-for

Interested in using v-for and I have encountered a scenario with an object structure as seen here: https://i.sstatic.net/wNguk.png Upon inspecting the dev console, the object looks similar to this: https://i.sstatic.net/jyqth.png My query is about how to ...

Utilizing regex patterns within Jqgrid

I am currently utilizing the JqGrid plugin (version 4.6.0 - jQuery Grid) to filter my results using specific fields. Here is an example of how the GUI appears: https://i.sstatic.net/BqGai.png With a large list of employees, I want the ability to filter t ...

Implementing Partial Login and Registration Views using AngularJS in conjunction with MVC5 and ASP.NET Identity

Embarking on the journey of creating a Single Page Application with log-in/register functionality using MVC5, ASP.NET Identity, and Angular feels like diving into a vast ocean of web development technologies. Despite being new to this realm, I delved into ...

Debugging Success Message Display Issue in JavaScript

$.ajax({ type: "POST", url:'/saveLayout', data: {id : layoutId, section : arrSection}, success: function(response){ $('#successMsg').addClass("errorBox"); document.getEleme ...

|Webview|Best Practices for Integrating Upload Script

I am currently developing an Android app using WebView and I need to implement a code for uploading on Android. I came across the following code snippet and I want to convert it into JavaScript instead of Java (if possible). It needs to be linked to the up ...

When viewing an array, the objects' values are displayed clearly; however, when attempting to access a specific value, it

I am attempting to retrieve the board_id of my objects in the columnsServer array... columnsServer: Column[]; this.service.getColumns() .subscribe(data => { this.columnsServer = data; console.log(this.columnsServer); for (this.i = 0; this.i ...

Duplicate multiple "li" elements using jQuery and place them in a designated position within the ul element, rather than at the end

I am currently working on developing a dynamic pagination bar. This pagination bar will dynamically clone the "li" elements based on a number received from an external webservice. Here is the structure of my pagination element: <ul class="pagination"& ...

Experiencing a problem with JQuery Offset when a fixed position is applied to a

My website has a page layout and style similar to the example provided in this JsFiddle. When I use JQuery to click on a button, the content is displayed correctly as shown below: https://i.sstatic.net/V89qa.jpg However, if I scroll down the page first ...

Exploring the World of jQuery Caching and Navigating Through Objects

I'm interested in learning more about jQuery caching and how it can enhance performance. Can you explain how to properly utilize this technique? From what I understand, when using a jQuery selector, you're essentially searching the DOM to create ...

incorrect calculation of date difference using momentjs

Currently utilizing countdown.js for a project where I need to add 60 days to a date fetched from the database. Successfully implemented this in the targetDay variable and it's functioning properly. However, when attempting to calculate this date fro ...

The combination of jQuery, using .load method in javascript to prevent scrolling up, making XMLHttpRequest requests, updating .innerHTML elements, and troubleshooting CSS/JS

While utilizing this code, CSS and Javascript are disabled (only HTML loads): function loadContent(limit) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status ...

Pressing a key will initiate a time delay before

I have a coding challenge where I need to navigate through a sprite sheet using setTimeouts. Everything is functioning as expected, but I am curious about implementing a feature that allows me to skip frames by pressing the "m" key. Essentially, I want it ...

Develop a diverse range of form types within Django forms

Even though I know how to create a form set based on a given form type, it doesn't completely resolve the issue at hand. Imagine having a fast food portal where users can add items and depending on their selection, additional fields need to be dynami ...

Strategies for managing a large volume of pending requests

I am looking to create a website that can notify users about events happening on the server. Here is my proposed plan: Send an asynchronous request to the server (ASP.NET) with a 600-second time-out If an event occurs on the server within those 600 secon ...

Is there a way to send data to FastAPI using JavaScript and AJAX?

I am facing an issue while attempting to send data using a request body to my server. I keep receiving an error message that says "value is not a valid dict" with the type_error.dict. The backend, which is built using FastAPI, seems to be functioning prop ...