Webinvoke to POST JSON with ajax call

Posted by G-Man on Stack Overflow See other posts from Stack Overflow or by G-Man
Published on 2013-11-09T09:49:38Z Indexed on 2013/11/09 9:53 UTC
Read the original article Hit count: 221

This is my first time that I an using WCF Service with Knockout. I want to POST an entire view model as a JSON object with an ajax call.

This is the error message that I get: Endpoints using 'UriTemplate' cannot be used with 'System.ServiceModel.Description.WebScriptEnablingBehavior'

I have noticed that some developers send each value as a parameter which I feel is unnecessary especially if you work with a big object.

This is my WCF method:

[OperationContract]
    [WebInvoke(UriTemplate = "AddNewEvent?newEvent", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    public bool AddNewEvent(Models.DAL_CRMEvents newEvent)
    {
        Entities.CRMEntities dbCRM = new Entities.CRMEntities();
        //Models.CRMEvents crmEvent = new Models.CRMEvents();
        Entities.Event crmEvent = new Entities.Event();



        crmEvent.EventDateCreated = Convert.ToDateTime(newEvent.DateCreated);
        crmEvent.EventActive = true;
        crmEvent.EventDescription = newEvent.Description;
        crmEvent.EventDate = Convert.ToDateTime(newEvent.Date);
        crmEvent.EventTimeStart = TimeSpan.Parse(newEvent.TimeStart);
        crmEvent.EventTimeEnd = TimeSpan.Parse(newEvent.TimeEnd);
        crmEvent.EventAllDay = newEvent.AllDay;

        dbCRM.AddToEvent(crmEvent);

        return true;
    }

This is my ajax function

function SaveEvent (data) {
        var s = {
            newEvent: ko.mapping.toJS(data)
        }


        alert(data.AllDay());
        $.ajax({
            type: "POST",
            url: "../Services/CRMDataService.svc/AddNewEvent",
            data: JSON.stringify(s),
            contentType: "application/json; charset=utf-8",
            dataType: "JSON",
            success: function (result) {
                alert(result);
            },

            error: function (jqXHR, textStatus, errorThrown) {
                if (textStatus == "error" && errorThrown != "") {
                    var n = noty({
                        text: errorThrown,
                        type: 'warning',
                        dismissQueue: false,
                        modal: true,
                        layout: 'center',
                        theme: 'defaults',
                        callback: {
                        }
                    })
                }
            }
        })
    }

© Stack Overflow or respective owner

Related posts about AJAX

Related posts about knockout.js