How to configure WCF RESTful endpoint for client-side jQuery calls - wcf-binding

Can some one show me how to configure the WCF Endpoint for the following RESTful Web Service to be called from a JQuery Ajax call. My example service code:
namespace MyService
{
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service
{
[OperationContract]
[WebGet(UriTemplate = "/GetDepartment")]
public Department GetDepartment()
{
... code
};
return data;
}
}
jQuery code:
var jData = {};
$.ajax({
cache: false,
type: "POST",
async: true,
url: "MyService/GetDepartment",
data: JSON.stringify(jData),
contentType: "application/json",
dataType: "json",
success: function (jsondata) {
... code
},
error: function (xhr) {
alert(xhr.responseText);
}
});

Try following-
function SaveBook() {
var bookData = {};
$.ajax({
type: “POST”,
url: “MyService/GetDepartment″,
data: JSON.stringify(bookData),
contentType: “application/json; charset=utf-8″,
dataType: “json”,
processData: true,
success: function (data, status, jqXHR) {
alert(“success…” + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}

Related

Why is the model binding not working? ASP.NET Core 5.0 RazorPages

ASP.NET Core 5.0 Razor Pages.
When posting the array, the model is not binding - value is showing empty array.
This is a JSON array posted using Ajax -
[
{ "Order":1, "FileName":"bbed5ecf-4133-4681-b0f3-c11366ad3186.jpg" },
{ "Order":2, "FileName":"737e60dc-0631-493d-947d-2f5948d7818c.jpg" },
{ "Order":3, "FileName":"6c76f9d1-44bd-4b80-926e-2ce4307eb30b.jpg"}
]
function UpdateImageOrder() {
$.ajax({
type: "POST",
url: "/property/imagesorter",
dataType: "json",
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
data: JSON.stringify(newOrderDictionary),
success: function (response) {
}
});
}
RazorPage action Method
public async Task OnPostAsync(ImageOrder[] data)
{
}
public class ImageOrder
{
public int Order { get; set; }
public string FileName { get; set; }
}
The data parameter of the POST should be the object value, not a stringified version of it. Try changing to:
...
data: newOrderDictionary,
...
Assuming newOrderDictionary is an array.
Considering using post to pass data, you need to add contentType:"application/json" in ajax.
$.ajax({
type: "POST",
url: "/?handler",
dataType: "json",
contentType:"application/json",
//...
});
In addition, add [FromBody] in the bakend.
public async Task OnPostAsync([FromBody]ImageOrder[] data)
{
}
Then, it can get the data.
Turns out that this works :
public async Task OnPostAsync(ImageOrder[] order)
{
}
function UpdateImageOrder() {
$.ajax({
type: "POST",
url: "/property/imagesorter",
dataType: "json",
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
data: {
order: newOrderDictionary
},
success: function (response) {
}
});
}

RazorPages return RedirectToPage not working

I've got an odd thing happening. On my index page I've got an ajax call that grabs a parameter off of an SVG and then hits the following code:
public async Task<IActionResult> OnPostStateClickAsync(string state)
{
HttpContext.Session.SetObject("CurrentFilters", SearchFilters);
SearchFilters.State = state;
return RedirectToPage("/Search");
}
I'm able to attach a debugger and see everything is working fine behind the scenes. The problem, the UI doesn't ever update and take me to the Search page. If I manually navigate there all the data is loaded and everything is fine.
Not seen this behavior before and I've used the same code in previous projects.
Here is the AJAX call in case it's relevant:
$(document).ready(function () {
$('path').click(function () {
var stateParameter = $(this).attr('id');
$.ajax({
type: "POST",
url: '/Index?handler=StateClick&state=' + stateParameter,
//data: searchTitle,
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
dataType: "json"
}).done(function (data) {
console.log(data.result);
location.reload();
});
});
});
You can change your code like bellow.
Action:
public async Task<IActionResult> OnPostStateClickAsync(string state)
{
//...
return new JsonResult(new { redirectToUrl = "/Search" });
}
In your Ajax:
$(document).ready(function () {
$('path').click(function () {
var stateParameter = $(this).attr('id');
$.ajax({
type: "POST",
url: '/Index?handler=StateClick&state=' + stateParameter,
//data: searchTitle,
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
dataType: "json",
success: function (response) {
window.location.href = response.redirectToUrl;
}
});
});
});
Test Result:

Passing form collection with Knockout.js in asp.net MVC

I am new to MVC and I am trying to create an application with Knockout.js to send data back to the server dynamically. I am following an example i found at:
http://www.mytecbits.com/microsoft/dot-net/knockout-js-and-bootstrap-with-asp-net-mvc-part-2
It works perfectly off the site, but i am trying to send data to multiple models instead just one as in the example
The Knockout code used in the example to send the data back to the server is
var urlPath = window.location.pathname;
var CreateArticleVM = {
Title: ko.observable(),
Excerpts: ko.observable(),
Content: ko.observable(),
Test: ko.observable(),
btnCreateArticle: function() {
$.ajax({
url: urlPath + '/Create',
type: 'post',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: function(result) {
window.location.href = urlPath + '/';
},
error: function(err) {
if (err.responseText == "success") {
window.location.href = urlPath + '/';
}
else {
alert(err.responseText);
}
},
complete: function() {}
});
}
};
ko.applyBindings(CreateArticleVM);
How do i modify the above code to be able to accept a FormCollection? Or what is the best solution to my problem?
Thanks
Say your service is expecting more than one argument like following.
[HttpPost]
public String Create(ModelA modela, ModelB modelb)
{
//Server code.
}
In order pass the data for Create method from client side you need to form your postdata as follows.
$.ajax({
url: urlPath + '/Create',
type: 'post',
dataType: 'json',
data: {modela: { "modela data in the expected form" }, modelb : { "modelb data.." } },
contentType: 'application/json',
success: function(result) {
window.location.href = urlPath + '/';
},
.
.
.
.
});

what's wrong when using jquery to call wcf service, always return internal server error?

Below is my jquery codes, and it always return internal server error, and i'm sure that my wcf service can be called from i.e and iis.
$.support.cors = true;
$.ajax({
type: "post",
url:"http://localhost:8080/WcfService/FunHeartWork.svc/UpdateMedia",
data: '{"desc":"' + text + '","albumId":"'+albumId+'","mediaId":"'+mediaId+'","userName":"'+userName+'"}',
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (result) {
alert(result);
},
error:function(a,b,c){alert(c);},
failure: function (msg) {
alert(msg);
}
});
Try changing the data line to:
data: {
desc: text,
albumId: albumId,
mediaId: mediaId,
userName: userName
},

how to call this calling WCF method continuously

I have an ajax enabled WCF service method :
[OperationContract]
public string Test(string name)
{ return "testing testing." + name; }
and I am calling it with following code:
$(document).ready(function () {
var varData = $("#NewSkill").val();
$("#Button1").click(function () {
$.ajax({
type: "POST",
url: "TimeService.svc/Test",
data: '{"name" : "John"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
});
});
I want to call this method continuously after every 5 seconds using above code . How can I do this ?
Move the $.ajax(); part to a Javascript function say AjaxCall(). Create a javascript variable
var isActivated = false;
$(document).ready(function () {
while(isActivated){
setTimeout("AjaxCall()",3000);
}
}
);
$("#Button1").click(isActivated = true)
Hope this helsps...