Showing posts with label javascript. Show all posts

Use Toastr messages from codebehind

1 comment
I have been using the excellent toastr library for my clientside messages now for a while.

Today I needed to send a message from codebehind to the client and I wanted to keep using toastr.

As I prefer to solve things only once I wanted this to be reusable through my app.
Something like:

var msg= new Message(Level.Error,"This is the text", "This is the title"));
viewmodel.Messages.Add(msg);

and then have this show up the nice toastr way:





(See demo over at GitHub for all the options.)


So to have a reusable way to send messages to my users with Toastr I came up with this model:


First I define a model for messages


Next I create a ViewModel class and inherit from it:



In the controller I can now easily add messages:




Add finally make them pop up in the view:






I can now add multiple messages with different levels, all from codebehind:



Post multiple values to WebAPi using jQuery

No comments


Javascript:

 $.ajax({
                    url: "/Api/AppointmentApi/MatchAppointment",
                    type: "POST",
                    dataType: "json",
                    data: JSON.stringify({ appointmentId: appointment.ID, contractId: contract.ID }),
                    contentType: "application/json; charset=utf-8",
                    context: this,
                    success: function (results) {
                        self.Untreated.remove(appointment);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        self.Info(textStatus + ": " + errorThrown);
                    }
                });

To post multiple values to a WebApi method you need to convert it first to a json string using JSON.stringify.

WebApi will correctly do the reverse transformation and rebuild the object:

WebApi/MVC:


        [HttpPost]
        public dynamic MatchAppointment(dynamic data)
        {
            int appointmentId = data.appointmentId;
            int contractId = data.contractId;

            var rslt=doSomething...
            return rslt;
        }