简体   繁体   中英

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:

在此处输入图像描述

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!

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 );
                });
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM