Utilizing GUID model binding within ASP.NET MVC

Can someone please assist me in resolving this issue? I've been struggling to find the solution and it seems like there's something obvious that I'm missing...

The problem I am facing involves sending a GET request from my JavaScript code, where the URL includes a Guid. However, the ASP.NET controller is not responding or registering the request to the API.

I have tried various approaches, but here is my current JavaScript code and Controller setup:

        function fetchConversation(contactId) {
            $.get("/contact/conversations", { contactId: contactId })
                .done(function(response) {
                       let chatData = response.data || [];
                       displayChat(chatData);
                });
        }

and...

    [Route("contact/conversations")]
    public JsonResult ConversationWithContact(Guid? contactId)
    {

      ... //this part is not being triggered

    }

Every time I attempt to run the script, I encounter this error message:

https://i.sstatic.net/SPN1q.png

I am unsure about how to correctly bind the Guid so that it can be received by the ASP.NET Controller. Any suggestions would be highly appreciated! Thank you and have a wonderful day!

Answer №1

Modify your path to the following:

[Route("~/contact/conversations/{id}")]
public JsonResult ConversationWithContact(string id)
    {

      if(!string.IsNullOrEmpty(id)){

   var contactId= new Guid (id);
      ... //this section is not being accessed
} 

    }

and update your ajax request:

function getChat( contact_id ) {
            $.get("/contact/conversations/"+contact_id)
                .done( function(resp) {
                       let chat_data = resp.data || [];
                       loadChat( chat_data );
                });
        }

however, if you are using an older version of MVC and attribute routing doesn't work for you, consider this approach:

function getChat( contact_id ) {
            $.get("/contact/ConversationWithContact/"+contact_id)
                .done( function(resp) {
                       let chat_data = resp.data || [];
                       loadChat( chat_data );
                });
        }

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

implementing one active line item at a time in Vue

Within my Vue template, I have a small unordered list: <ul style="border-bottom:none !important; text-decoration:none"> <li class="commentToggle" v-bind:class="{active:commentActive}" v-on:click="setInputName('new')">New Comment ...

Error encountered during Jest snapshot testing: Attempting to destructure a non-iterable object which is invalid

I am currently facing an issue with my React codebase where I am attempting to create snapshot tests for a component. However, Jest is showing an error indicating that I am trying to destructure a non-iterable instance. Despite thoroughly reviewing the cod ...

The parent div of the clicked hyperlink is not displaying the ajax response

I have a problem with my code. I want to make an ajax request whenever a hyperlink is clicked and render the response in the parent div of that hyperlink by replacing the hyperlink itself. Despite trying different codes and searching online, I am unable to ...

Delete any HTML content dynamically appended by AJAX requests

I'm currently working on a page dedicated to building orders, where the functionality is fully dependent on ajax for finding products and adding them dynamically. However, I encountered an issue when attempting to remove an item that was added via aj ...

Click to load an IFRAME upon clicking

I am encountering an issue with IFRAMEs loading onClick. The problem lies in the script provided below which always loads the content of the first iframe, whereas my expectation is to load only the iframe corresponding to the link clicked. $('.toggle ...

Divide JSON information into distinct pieces utilizing JQuery

$.ajax({ type: 'POST', url: 'url', data: val, async: false, dataType: 'json', success: function (max) { console.log(max.origin); } ...

After implementing ajax jQuery with Laravel 10, this page is experiencing technical difficulties

Seeking assistance from experienced individuals in dealing with Ajax jQuery within the context of Laravel. I have encountered a problem that has proven difficult for me to resolve on my own. Sample html code: <li> <a href="" onclick ...

Extracting the value of an attribute from an XML element and converting it into an HTML unordered list with

Here is an example of an xml file structure: <root> <child_1 entity_id = "1" value="Game" parent_id="0"> <child_2 entity_id="2" value="Activities" parent_id="1"> <child_3 entity_id="3" value="Physical1" parent_id="2"> ...

On successful completion of the $.post request, hide a group of div elements with a fade-out

I need help fading out a set of div elements based on the response received from an ajax call. The current code I have doesn't seem to be doing what I intended. Can someone point out where I might be going wrong? $('.view_result').click(fu ...

Navigating through each segment

I'm currently working on a website with sections that are set to be 100% height of the window, but at least 800px tall. My goal is to implement a smooth scrolling functionality where one scroll moves the view from section to section. However, if the ...

Angular has the ability to round numbers to the nearest integer using a pipe

How do we round a number to the nearest dollar or integer? For example, rounding 2729999.61 would result in 2730000. Is there a method in Angular template that can achieve this using the number pipe? Such as using | number or | number : '1.2-2' ...

When working with Angular 2 and Typescript, a common error message that may be encountered is "TypeError

Currently diving into Angular 2 and encountered a stumbling block while attempting to create a service. Despite my efforts in finding a solution, I seem to be missing something crucial. Error: A problem arises in angular2-polyfills.js:1243 with the error ...

"Using only JavaScript to target and manipulate child elements within the

I'm currently transitioning from using jQuery to pure JavaScript, and I've just started but am encountering difficulties. Specifically, I am unsure how to select child elements in the DOM. <div class="row-button"> <input type="submi ...

Having trouble getting the JavaScript function to run when clicking a button inside a div or form?

Hey there, so I've got this scenario where I have a button nestled within a div. Take a look at the HTML snippet below: <div class="row"> <button type="button" id="submit">Send</button> </div> Prior to this button, there ...

Original: Default Sharepoint 2010 TabsRewritten: Share

I've scoured through various sources like stackoverflow and google in search of a solution to my issue, but unfortunately, I haven't found anything that has worked. Currently, I am working on a project using Sharepoint 2010 with Portuguese trans ...

New navigation menu changes as user scrolls

I'm struggling to find a way to implement a different navigation menu that appears when the user scrolls down. I'm envisioning something similar to this example: My goal is to have #small-menu replace #big-menu once the user starts scrolling. C ...

Angularfire2: Access Denied Error When User Logs Out

When utilizing the following method: login() { this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider()) .then(() => { this.router.navigate(['']); }); } An error occurs during logout: zone.js:915 Unca ...

Creating a Map in TypeScript from an Array

I have a series of TypeScript objects structured like this: interface MyObject { id: string, position: number } My goal is to transform this array into a map format where it shows the relationship between id and position, as needed for a future JSON ...

What is the best way to create a dynamic textbox or label within a specific div class?

I need assistance with my dynamic asp.net page where I am generating labels and text boxes in a form. Is there a way to ensure that these elements are generated within a specific div class? Below are the relevant code snippets: for (int i = 0; i < cou ...

Error alert: TypeScript typings issue - Naming conflict with Promise / Failure to locate name Promise

I am currently working on a client/server JavaScript application and I am facing a significant issue with Promises. It appears that they are either undefined or duplicated, and this problem seems to be related to the @types package. npm install --save @ty ...