Saving changes to a jQuery sortable table - c#

I have a table where the users are allowed to drag and drop rows in the order they want, and then save them. I have no problem with getting the drag and drop part to work. It's the saving I'm having issues with. I'm sending an Ajax call to a web service which will then make the save. I can't seem to actually catch the request in the web service though.
My JavaScript function looks like so:
$(document).ready(
function () {
$(".sortable").sortable({
update: function () {
serial = $('.sortable').sortable('serialize');
$.ajax({
url: "MyWebService.asmx/SortTable",
type: "post",
data: serial,
error: function () {
alert("theres an error with AJAX");
}
});
}
});
});
The JSON string looks fine from what Firebug is showing me. The web service function is like so:
[WebMethod]
public string SortTable(String[] rows)
{
//SaveChanges();
return "Called!";
}
When I put a breakpoint in there, it never gets hit. When there are no arguments in the function though, it will get hit. I've tried replacing "String[]" with "object" and it still doesn't get hit, which I find odd. What is going on here?

You might need to decorate your web service with the [ScriptService] attribute in order to allow client scripts to invoke it. Also if you are sending a JSON request you need to specify the content type. Another remark is about sending the request as an actual JSON object which could be achieved using the JSON.stringify method (maybe the $('.sortable').sortable('serialize') call already does this, I am not familiar, you just need to ensure that the POSTed value looks like this: [ 'row1', 'row2', ... ]):
$.ajax({
url: 'MyWebService.asmx/SortTable',
type: 'post',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify([ 'row1', 'row2', 'row3' ]),
error: function () {
alert('theres an error with AJAX');
}
});

Related

Sending $ajax via jQuery to C# codebehind not working

I am having unexplained behavior when I post from jquery using ajax to C#.
1) The main page is called not the method I am requesting in jQuery.
To work around this I simply put an if in the page load so that if a particular item is in the querystring it will trigger a series of commands. It does hit that if statement and runs the code perfectly fine. There are some methods that do things like change a color on the map. These never actually happen. I can set a label and it will pass right over it but the label remains unset.
2) strangely enough.... my page has a timer with a refresh on it. It refreshes the page and now the changes are processed.
Here is the way I am calling my method in jQUery:
function mycmethod(param)
{
//alert(precinct);
$.ajax({
url: "myPage.aspx/someMethod",
type: 'POST',
data: "params=" + param,
success: function iGotData(responseJSON) {
// alert("Worked");
},
error: function (xhr, status, errorThrown) {
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.log(xhr);
alert("Didnt work:" + errorThrown);
},
})
};
It was originally set to async: true but that didn't make a difference.
The method its not calling on load is:
[WebMethod][ScriptMethod]
public Boolean someMethod(string param)
{
setFeatures();
GenerateMap();
return true;
}
I doubt its relevant but I am calling a jquery call with over mouse over of a specific element. That jquery calls a function which calls a asmx web service that returns some jSON. I am calling the mycmethod after the JSON is returned.
Why is my UI elements not responding until the page refreshes. If not, is there a way I can force a refresh like the timer does?
[WebMethods] methods should be declared as static.
I've also found that you might need to specify the content type in your ajax call:
contentType: "application/json; charset=utf-8"
Also, your data option looks suspicious. Maybe you should append it to the url option:
url: "myPage.aspx/someMethod?params" + parm
or, more ideally, send it as either a JSON object or a JSON string:
data: {
params: param
}
or
data: JSON.stringify({
params: param
})
If I understand you correctly, you're loading the page, then calling the server via ajax and expecting the server to change UI elements of the currently loaded page.
It doesn't work like that, unfortunately. Once you've served the page, the server itself cannot manipulate that page without doing a refresh/post back (or something along those lines).
If you want to update the UI without doing a refresh/post back you can have your WebMethod return HTML, and your jQuery success method can update the relevant controls.
Alternatively you could use jQuery's .get() to retrieve a fresh copy of the page via ajax, and update your current page like that. (although it's less efficient)

Sending data from controller to javascript using Linq 500 internal server error mvc2

C#
public ActionResult SimpleQuery()
{
ClientDataContext dc = new ClientDataContext();
var userResults = from u in dc.TS_Trucks select u;
return Json(userResults.ToList(), JsonRequestBehavior.AllowGet);
}
Javascript
$.ajax({
url: '#Url.Action("SimpleQuery")',
type: 'GET',
dataType: 'json',
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
I don't even use the data in the JavaScript, something about the way I'm passing it is probably the problem but can't seem to figure it out.
you need to specify the controller for your url helper. The server error is from trying to locate your action. Try this for the ajax url:
'#Url.Action("SimpleQuery", "<ControllerForYourActionHere>")'
Internal Error usually infers bad URL address.
In this case, url parameter is not set to right value.
First, you need to check which Router map to this function: SimpleQuery
Then, use that address to fill in url parameter.
Also, I don't think '#Url.Action("SimpleQuery", "<ControllerForYourActionHere>")' will work if you put
it in javascript file. It might works in cshtml file.
So, the conclusion is when you are doing frontend programming, use absolute link will be a good idea.
It make sure you hit the right address at the first time.

$.ajax POST call to ServiceStack webservice, parameter not arriving

I am trying to learn how to program a web service with ServiceStack and call it via ajax in JavaScript. I did this by watching the pluralsight movies and I think I almost figured it out how to do that except for passing data as parameters with a service call.
I try to call the service with this ajax-call:
var request = { };
request.Amount = 32;
$.ajax({ type: 'POST',
contentType: 'application/jsonp; charset=utf-8',
url: "http://localhost:1879/entry",
dataType: 'jsonp',
data: {request: request},
success: function(result){
alert(result.Id);
}});
The service looks like this:
public class EntryService : Service
{
public object Post(Entry request)
{
return new EntryResponse() { Id = request.Amount };
}
}
[Route("/entry", "POST")]
public class Entry
{
public int Amount { get; set; }
}
public class EntryResponse
{
public int Id { get; set; }
}
I expect the alert in the callback to show the number 32, but it shows the number 0. And when I debug my service I see that request.Amount is 0 as well, so I think I do something wrong at the Ajax service call but I cannot figure out what. So I wonder what I am doing wrong here.
author of that Pluralsight course here. Hopefully I can help you.
First thing you should do is make sure the API is working correctly.
Go to this: http://localhost:1879/entry
In your web browser you should see a page displayed that has information about the service. If you don't your URL is wrong or ServiceStack is configured wrong.
Assuming the URL is correct, all you should need to do is wrap your data in JSON.Stringify().
When you do a post, the data has to be in JSON format as a JSON string. You are currently sending a JSON object.
Also, most likely you can drop the localhost bit off your url in the $.ajax call and just do "entry"
You can not do a post with JsonP. If you are trying to do a cross domain POST you need to look into cors and make sure that is enabled for the the service you are POSTing to.
Post data to JsonP
I only used jsonp cause I read and hoped that it could be the solution for my problem. But based on your explanation I shouldn't need it, so I changed my code to this:
var request = { };
request.Amount = 32;
$.ajax({ type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "http://localhost:1879/json/reply/Entry",
dataType: 'json',
data: request,
success: function(result){
alert(result.Id);
},
error: function(xhr, ajaxOptions, thrownError){
alert("Failure!");
alert(xhr.status);
alert(thrownError);
}});
First I had this call without the error part and nothing happened, no alert, no error, nothing. So I assumed the error was consumed instead of being showed, so I added the error callback and my assumption seemed to be right. Now I get 3 alerts and the last 2 alerts shows "400" and "bad request".
I searched on those errors and tried but none of the possible solutions I found fixed my problem. I tried 2 urls: /json/reply/Entry and /entry after the localhost part but both didn't work. So what am I doing wrong?

Cross Domain jQuery Ajax Using C# and WFC

I have a small webservice written in C# and WCF.
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello Worlds";
}
}
I have a little jQuery code;
$.support.cors = true;
$.ajax({
type: "POST",
url: "http://localhost:61614/Service1.asmx/HelloWorld",
data: '{}',
dataType: "json",
success: function (msg) {
alert(0);
}, error: function (a, b, c) { alert("Err:" + c );
}
});
This calls the webservice. There are no problems making the call, but it errors out on the return.
The webservice is in one application, and the Web page is simply an HTML page on it's own. Eventually, the HTML will be used within PhoneGap.
I have tried all sorts of things.
Adding in contentType: "application/json; charset=utf-8", causes the whole call to fail.
Using dataType: 'jsonp" causes call to fail.
Basically, the above calls the WS but errors out on return which is weird.
My requirement is that I need to return a JSON object from the webservice, and it has to work in Safari.
Does anyone have complete sample code of a JSONP call?
From jQuery getJSON:
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.
In order for your request to be treated as a JSONP request, you need to include callback=? in your URL. This tells jQuery to create a callback function and pass the name of that function as the callback parameter to your server.
In the server-side code, your method must then return JSON code wrapped, or padded, with the name of the JavaScript function passed in as the callback parameter in the query string.
Essentially, what you're doing is returning JavaScript to the client browser, which runs immediately, and invokes a function already defined in the context of the page.
JavaScript:
$.getJSON("http://localhost:61614/Service1.asmx/HelloWorld?callback=?",
function(data) {
// alert raw JSON data
alert(JSON.stringify(data));
// access the "say" property and alert it
alert(data.say);
}
);
Server-Side:
This is a crude version of what you'd need to do on the server-side:
// get the callback parameter value and assign to the String callback
...
return callback + "( { 'say' : 'HelloWorld' } );";
Further technical explanation of what is happening under the hood:
While this is not something you need to know today, this may help you understand more about how jQuery is implementing JSONP.
This evaluates to something that might look like this:
return "jquery43214321432143242({'say':'HelloWorld'});"
where jquery43214321432143242 is the random name given for your success callback function. Again, since the returned text is returned using text/javascript, it runs immediately, passing the {'say':'HelloWorld'} object in as a parameter to the function.
The resulting output should be an alert message representing the raw JSON, and the words "HelloWorld", pulled from the .say property.

jQuery does not load response

I normally use ASP.NET MVC 2, but there were some problems with it, so I began to work with ASP.NET MVC 2 + jQuery and everything works. But there is one problem, jQuery doesn't load my reponse. On the ASP.NET MVC side I'm redering a partial view and I also get the respone on the client, but nothing is rendered. How can I solve this?
Here is the jquery code:
function addCredential(state, id) {
var daten = getJson(state, id);
$.ajax(
{
type: "POST",
url: "/Account/SetCredential/",
data: daten,
dataType: "json",
success: function(partialView) {
$('#Credentials').replaceWith(partialView);
location.reload();
}
});
return true;
};
function getJson(state,id) {
var username = $('#username').val();
return {"username": username, "credential_id": id , "state": state };
};
The problem looks like location.reload();
That's reloading your page after you update it with AJAX, effectively returning it's state back to the way it was before you inserted the content with .replaceWith()
UPDATE: looks like you're using dataType: "json" and inserting that into the DOM? That's probably also a problem. If the view is being returned as HTML, you should replace that with dataType: "html"
#Konrad, try using the JSON2 library (http://www.json.org/js.html) to alert the "partialView" object in your success function to see what you're getting prior to reloading the page. Also, make sure $('#Credentials') is returning an object. When I run into issues when trying to select elements on the page, I usually check the length value of the jQuery object that is returned. If length = 0, then you're not getting the element.
UPDATE:
Also, if you're trying to inject HTML into $('#Credentials'), then partialView may not be the correct format. The success function accepts an object argument which comes from parsing of the responseText of the web method you called to get what you call partialView.
UPDATE:
Check http://encosia.com/2010/03/03/asmx-and-json-common-mistakes-and-misconceptions/ for more info using $.ajax. Lots of great info on this blog.
UPDATE:
This is how I use JSON lib to view the data that is returned.
alert(JSON.stringify(partialView));

Categories