Skip to content
Advertisement

GUID model binding in ASP.NET MVC

I was hoping someone could help me sort this out. The solution to this is probably obvious but I can’t seem to figure out what I’m missing…

I’m trying to issue a get request from my Javascript code, and the URL contains a Guid. The ASP.NET controller does not get hit/register the request to the API.

I’ve tried a couple different things already but this is my Javascript and Controller as is:

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

and…

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

      ... //this doesn't get hit

    }

I keep getting this error:

enter image description here

I’m not sure how to properly bind the Guid such that it is received by the ASP.NET Controller.

Any ideas?? Much appreciated and have a great day!

Advertisement

Answer

Change your route to this:

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

      if(!string.IsNullOrEmpty(id)){

   var contactId= new Guid (id);
      ... //this doesn't get hit
} 

    }

and your ajax:

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

but if you use very old MVC and attribute routing doesnt work for you, try this:

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

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement