Exploring the power of Ajax within the MVC framework

I'm attempting to incorporate a view through Ajax, but I'm encountering some issues. My knowledge of Ajax is limited, but I am eager to learn. What could be the missing piece here, or am I completely off track with my approach?

    foreach(ect...) {
   <tr>
       <td>
      <a href="#" onclick="AjaxStoryClick(@item.Id)" style="color:dodgerblue; font-weight: bold">@item.Name</a>

       <script type="text/javascript">
function AjaxStoryClick(storyid) {

    $.ajax({
        url: '@Url.Action("UserStoriesList", "Estimate")',
        type: 'POST',
        data: storyid,
        success: function(result){
            $('#stories').html(result);

        }
     });         
}    

      </script>

Controller:

       public ActionResult UserStoriesList(int id)
    {
        ActiveEpicId = id;
        var userstories = userRepository.Select().Where(x => x.EpicId.Equals(id)).ToList();
        return PartialView("UserStoriesList",userstories);
    }

Answer №1

Is the Action method UserStoriesList set to type HttpPost? Since your Ajax request is a POST, it will only be processed by an HttpPost type UserStoriesList action method.

[HttpPost]
public ActionResult UserStoriesList(int id)
{
  // Add your code here
}

If your ActionMethod is not of type HttpPost (meaning it is of type HttpGet), you can use a jQuery get ajax call to retrieve the data.

Ensure that the parameter name in your ajax call matches the parameter name in your action method.

function AjaxStoryClick(storyid) {
  $.get('@Url.Action("UserStoriesList", "Estimate")',{id : storyid},function(result){
     $('#stories').html(result);
  });
}

}

Answer №2

The issue with the Ajax call is that it is not passing the value for the parameter 'Id' to the action method 'UserStoriesList'. In line 'data: storyid,', it should be 'data: { id: storyid},'

Since your action method 'UserStoriesList' has a non-null parameter for id, the server will generate an error response.

If there is no callback for the ajax error event, you will not see the error response. Additionally, in debug mode, the breakpoint in the action will not be hit.

Below is the updated script:

<script type="text/javascript">

function AjaxStoryClick(storyid) {

 $.ajax({
    url: '@Url.Action("UserStoriesList", "Estimate")',
    type: 'POST',
    data: { id: storyid },
    success: function (result) {
        $('#stories').html(result);
    },
    error: function (xhr) {
        alert("Error: " + xhr.responseText);
    }
 });
}
</script>

Action method:

public ActionResult UserStoriesList(int id)
{
  ActiveEpicId = id;
  var userstories = userRepository.Select().Where(x => x.EpicId.Equals(id)).ToList();

  if (Request.IsAjaxRequest())
    return PartialView("_UserStoriesList", userstories);
  else
    return View("UserStoriesList", userstories);
}

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

What is the reason onbeforeunload does not fire requests in Safari browser?

Is there a way to ensure that data is saved to the database when a user interacts with the page and also when they refresh it? I have tried using onbeforeunload event, but Safari does not wait for the server request to finish before reloading the page, c ...

The error message "Next.js 14 does not recognize res.status as a function"

I'm a newcomer to Next.js and I've been wrestling with an issue all day. Here's my API for checking in MongoDB if a user exists: import {connect} from '../../../../lib/mongodb'; import User from '../../../models/userModel&ap ...

Is there a way to activate ng-change when a space character is input?

My function is triggered when the value of a textarea changes, however, it does not work when the spacebar is pressed. Is there a way to make it work for spacebars as well? I want the function to be called whenever the content changes, regardless of the ke ...

Deleting a Virtual Directory in IIS

I currently have a website displayed below. My goal is to eliminate the virtual path known as "devtest". https://i.sstatic.net/ISp0D.png Even after attempting the following code, the "Application" always returns null. private static void RemoveV ...

Unable to send data through ajax to razor pages

I'm encountering an issue where the data I'm trying to send to a Razor Page method always comes through as 0. Here's the code: Razor Page: public IActionResult OnGetProducts(int page) { var products = _productRepository.GetProducts(); ...

Issue with Angular Swiper carousel: Error message pointing to node_modules/swiper/angular/angular/src/swiper-events.d.ts

I am attempting to implement a carousel in Angular using Swiper (). An error message is appearing: Error: node_modules/swiper/angular/angular/src/swiper-events.d.ts:3:50 - error TS2344: Type 'SwiperEvents[Property]' does not meet the constraint ...

discovering the category for the .click function

After retrieving a list of book objects from a JSON object, I am in the process of displaying them on an HTML page by creating buttons with titles. The goal is to alert the URL of the book when a button is clicked. However, I am facing an issue with access ...

The Module Design Pattern in Jquery

In my project, there is a jQuery module pattern that I am having trouble understanding its purpose. There is also a custom plugin called jquery.skInit.js (function($) { $.fn.skInit = function() { return this.each(function(i,element) { var e = ...

Obtaining an IP Address from an FTP Request using C#

Currently, I am in need of assistance with an incoming FTP request. Specifically, I am trying to extract the IP Address of the FTP server that is mentioned in the request. This information needs to be cross-referenced with a set of whitelisted FTP servers. ...

Enhance your AJAX requests with a retry mechanism when incorrect payloads are sent in subsequent requests

Currently, I am working with Angular and RXJS and facing an issue where I need to execute up to 5 AJAX requests concurrently. Each request should be attempted up to 3 times before giving up and returning an error. The problem I'm encountering is that ...

Pass a byte array from the back-end code to an AJAX request

I have a web method where I am converting HTML to PDF and saving it to a local folder. The goal is for the user to download the file without needing to reload the page. To achieve this, I am attempting to make an AJAX POST call to the web method to retriev ...

How should the directory be organized for the param with a prefix in Nuxt.js?

My route is set up as /en/rent-:productSlug How should I organize the directory for this route, considering that the parameter productSlug includes the prefix rent? ...

Error message: The property or method "Name" is not defined on this object, but it is being referenced during the rendering process

Currently facing a challenge in implementing the modal closure functionality within the Vue.js template. Take a look at the code snippet: var modalInstance = new Vue({ el: "#modalInstance", data: { displayModal: false } }); Vue.compo ...

Utilizing the jQuery index for organizing JSON keys

Recently, I came across an interesting issue with a jQuery event handler in my code. When clicked, this specific event creates a JavaScript object based on a list of favorite links: $('#saveFavorites').on('click', function(){ a ...

The process of sending parameters to an API in ReactJS: a guide

My objective is to target .....the values originating from login (can be anything)-> for example email:'[email protected]' password:'12345678' I am required to extract the username until "@" and use it as a username i ...

Is there a way to stream audio directly from a URL on the client-side using ASP.NET?

I am currently working on a web page for an ASP.NET application using .NET Framework Version 4.0 and ASP.NET Version 4.7. My goal is to incorporate audio playback from a server. The specific URL I am dealing with is as follows: . However, I am struggli ...

Implementing pagination in React: A step-by-step guide

I am fetching data from the GitHub API, specifically from here Although I have all the necessary data to display, I want to limit it so that only 20 repositories are shown per page. In addition, I prefer not to use any frameworks or plugins for this task ...

What is the quickest method to identify duplicate entries within a JavaScript array?

let items = ['test0','test2','test0']; In the scenario shown above, we have two duplicate elements with the value "test0". What is the most efficient way to check for this duplication? ...

Incorporating an NPM module with dependencies within the Meteor framework

I'm encountering some difficulties while attempting to integrate an NPM package into my meteor project. The specific module I am trying to utilize is the steam package. In order to make this work, I have included the meteorhacks:npm package for mete ...

Processing a bulky JSON document in C#

1) Struggling to find a solution for downloading a large JSON file on a Windows Phone app? Want to process the JSON data as it's being downloaded to avoid long wait times? Looked everywhere for a fix but nothing seems to work... 2) Curious if there i ...