0

I have a messaging system inside a view of MVC that gets all the data from model. I have a ajax call in that view to a Web API that updates the database when somebody sends a reply or new message. I would like callback function to run so it updates the part of the screen that shows all chat messages from messaging system.

Jquery Ajax call

   <script>
        $(document).ready(function () {
            $("#sendMessage").on("click", function (e) {
                e.preventDefault();
                var MessageReplyParam = $('#messageToBeSent').val();
                var FromUserNameParam = $('#FromUserName').val();
                var FromUserIDParam = $('#FromUserID').val();
                var ToUserNameParam = $('#ToUserName').val();
                var ToUserIDParam = $('#ToUserID').val();
                var button = $(this);
                $.ajax({
                    //url: "/api/messages/SendMessages?MessageID=" + button.attr("data-message-id"),
                    url: "/api/messages/SendMessages",
                    method: "POST",
                    data:{
                        lngMessageID: button.data("message-id"),
                        Reply: MessageReplyParam,
                        FromUserID:FromUserIDParam,
                        FromUserName:FromUserNameParam,
                        ToUserID: ToUserIDParam,
                        ToUserName: ToUserNameParam                   
                    },
                    dataType: 'html',
                    success: function (data) {
                        $('#partial').html(data);
                    }
                });      
             });
        });

    </script>

Web API

 public HttpResponseMessage SendMessages([FromBody]MessageReply message)
        {
            //Add a message to MessageReply table
            dynamic model = new { Name = "" };
            _context.MessageReply.Add(message);
            _context.SaveChanges();

            var messagesReplies = from mrp in _context.MessageReply
                                  where mrp.lngMessageID == message.lngMessageID
                                  select mrp;

            List<MessageReply> MessageReplies = new List<MessageReply>();
            MessageReplies = messagesReplies.ToList();
            var response = new HttpResponseMessage();
            response.Content = new StringContent(@"<div class='messages'><div class='bg-dark rounded padding-x4'>
                                                  <span>test</span></div></div>");


            response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
            return response;

        }

Controller

   public ActionResult BookingInfo(BookingViewModel bvm, int? BookingId)
        {

            //This class will be used from All Bookings Link by passing in BookingID

            //Get the data from bookingID and show the booking details with messages
            //and option to send message
            BookingViewModel bvl = new BookingViewModel();

            if (Request.IsAjaxRequest())
            {
                return PartialView("_MessagesView", bvl.MessageReplies);
            }

            var BookingInformation = from booking in _context.Booking
                                     join pets in _context.PetInformation
                                     on booking.BookingID equals pets.lngBookingID
                                     join customer in _context.Customers
                                     on booking.ServiceProviderID equals customer.strUserID
                                     join requester in _context.Customers
                                     on booking.strUserID  equals requester.strUserID
                                     join msg in _context.Messages
                                     on booking.BookingID equals msg.lngBookingID into mt
                                     from submsg in mt.DefaultIfEmpty()
                                     where booking.BookingID == BookingId
                                     select new { bk = booking, pt = pets,cst = customer, req = requester,mst = submsg};

            //Get Message Replies


            int messageId = 0;

            foreach (var bi in BookingInformation)
            {              
                bvl.Booking = bi.bk;
                bvl.Pets = bi.pt;
                bvl.ServiceProvider = bi.cst;
                bvl.ServiceProviderName = bi.cst.Name;
                bvl.RequesterName = bi.req.Name;
                bvl.Booking.strUserID = bi.bk.strUserID;
                bvl.Booking.ServiceProviderID = bi.bk.ServiceProviderID;
                messageId = bi.mst.MessageID;
                bvl.Messages = bi.mst;
            }

            if (bvl.Booking.ServiceProviderID == User.Identity.GetUserId())
            {
                bvl.FromUserID = bvl.Booking.ServiceProviderID;
                bvl.ToUserID = bvl.Booking.strUserID;
                bvl.FromUserName = bvl.ServiceProviderName;
                bvl.ToUserName = bvl.RequesterName;
            }
            else
            {
                bvl.FromUserID = bvl.Booking.strUserID;
                bvl.ToUserID = bvl.Booking.ServiceProviderID;
                bvl.FromUserName = bvl.RequesterName;
                bvl.ToUserName = bvl.ServiceProviderName;
            }

            var  MessageReplies = from msg in _context.MessageReply
                                  where msg.lngMessageID == messageId
                                  select msg;

            if (MessageReplies.Count() > 0)
            {
                bvl.MessageReplies = MessageReplies.ToList();
            }

            return View("RequestBooking", bvl);
        }

View

 <div id="partial">

            @{
                Html.RenderPartial("_MessagesView",Model);
            }
        </div>

I would like that Div messages to load again with new messages once we get success from jquery callback. Is that possible? Do I have to write my HTML in my Web API to run through list and create HTML out of that? That will be a messy solution

Learn AspNet
  • 1,192
  • 3
  • 34
  • 74
  • 1
    Try [this](https://stackoverflow.com/questions/1371031/asp-net-mvc-partial-view-controller-action). You'll need a controller method that returns just the partial view that you want to display. You might want to do a second request. When you get the success from the update, send another request for the partial view containing all of the messages. It will return HTML. Then, whatever element contains that HTML, replace it with the new HTML. – Scott Hannen May 15 '19 at 20:03
  • @ScottHannen Thank you but I am still trying to get this working. Can you help a little with writing some code, I create the messaging part to be a partialView and I am rendering it using @Html.Partial("_MessagesView"). What should by API return? should that be object of newly created message? – Learn AspNet May 15 '19 at 20:26
  • 1
    It wouldn't be an API that returns data. It would return HTML. So just as in your controller you have a method that returns the full page view, you'll have a method that returns just the partial view. You'll make an ajax request to that method, and the response you receive back will contain HTML. When you get that response you overwrite the old HTML with the new HTML. – Scott Hannen May 15 '19 at 20:34
  • @ScottHannen Thank you Scott, I do understand the concept but I am struggling with the code. My call back function does not return anything so data is empty. In my callback function success: function (data), data is empty string. What do I need to pass back the model data or new database data? – Learn AspNet May 15 '19 at 20:42
  • Can you post the controller method that returns the partial view? – Scott Hannen May 15 '19 at 21:10
  • @ScottHannen Thank you scott, I have updated the code with controller and changed the Web API to return HTML. Do I have to create HTML myself to return list of messages, won't that be very messy way to doing things? – Learn AspNet May 15 '19 at 21:25
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/193425/discussion-between-learn-aspnet-and-scott-hannen). – Learn AspNet May 15 '19 at 21:31

0 Answers0