How to deserialize in C# something that was serialized in JQuery? - c#

. .
It's been a while since I've done this, and I'm trying to shake off the rust.
I'm trying to set up an AJAX structure in ASP.NET using VS2010.
I have a JQuery form submit that looks something like this (greatly simplified for example purposes):
function FormSubmit () {
$.post('SomeHandler.asmx/SomeFunction',
$("#form1").serialize(),
function(data) {some data handler}
);
}
My "SomeHandler.asmx/SomeFunction" is a C# function that takes my form data and processes it.
To my knowledge, the SomeHandler.asmx assumes XML deserialization, but the JQuery serializes it as an HTML encoded string, not as XML.
I suppose to use an analogy, one side is speaking in English, but the other side is expecting to hear French.
How do I get around this? (For example purposes, let's say my form has a text field -- we'll call it "txtField", and a drop-down list -- let's call it "lstDropDown".)
Thanks in advance for your help!

In your asmx file make sure you use the following attribute flags on your web methods that accept and respond with json:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string SomeWebMethod()
{
//blah
}
Also, make sure the web service class has the follow attribute flag:
[System.Web.Script.Services.ScriptService]
public class MyWebService : System.Web.Services.WebService
{
...
}
One last thing: if you're serializing the data on the client side, you need to use the following ajax setup:
$.ajaxSetup({ contentType: "application/json; charset=utf-8" });

Related

I have looked at calling c# through ajax, my implementation doesnt hit the c# method when I put a break point

My javascript to invoke the method in my c# class, the ajax call does get into success method but it does hit the c# method when I put in the break point. I tried changing the shoppingcart.aspx to shoppingcart.aspx.cs but still doesn’t hit the c# method.
<script type="text/javascript">
$('.removeCart').click(function (e) {
$.ajax({
type:"POST",
url: "ShoppingCart.aspx/deleteSelectedProduct/",
success: function () {
console.log("ITS GOING THROUH",e.target.dataset.removename);
},
error: function () {
}
});
});
</script>
my c# code
public void deleteSelectedProduct()
{
}
To troubleshoot
You should remove method name and put url of page as following
url: "ShoppingCart.aspx",
and put a break point on Page_load event if it hits the break point that means your url is fine now you can put complete url with method name.
url: "ShoppingCart.aspx/deleteSelectedProduct/",
Now you can check whats wrong with your method following are possible solutions
Your method deleteSelectedProduct should be static method
You'll need [WebMethod] decoration above your function deleteSelectedProduct
You'll need [WebMethod] decoration above your function in the aspx page.
I think you are missing starting / only. Correct the url like below:
url: "/ShoppingCart.aspx/deleteSelectedProduct/",
Give it try and let me know if it doesn't work.
The method you are trying to access using ajax call should be decorated with WebMethod attribute to enable ajax calling(#Dominic already suggested that, I am just describing it as a solution). It should be something like:
[System.Web.Services.WebMethod]
public void deleteSelectedProduct()
{
//implementation code
}
Or Include System.Web.Services as namespaces on top of the page and used directly WebMethod.
Cheers!!
You have to decorate the C# function with the WebMethod which will be in System.Web.Services.WebMethod.

Cannot make a call to Page WebMethod using jQuery Ajax?

I am currently trying to develop a chat applicaiton in asp.net2.0 and requires me to make a call to aspx Page Webmethod.My issue is that i cannot make a call to the page webmethod.
Not showing any message in error console of ff,so cannot findout where i have gone wrong.There is no issue while making a call webservice.
Heres the code i have writtern
$(document).ready(function(){
$("#btnSend").click(function(){
$.ajax({
type:"POST",
data:"{}",
url:"Chat.aspx/GetTime",
contentType:"application/json; charset=utf-8",
dataType:"json",
success:function(msg){
alert(msg.d);
},
error:function(msg){
alert(msg.d);
}
});
});
});
This is my chat.aspx page.The GetTime function is not getting called?Is the issue with the url ??
[WebMethod]
public static string GetTime()
{
return DateTime.Now.ToString();
}
Three things I would look at are:
1.) I'm wasn't sure that ASP.NET 2.0 could use the JSON AJAX stuff. I thought that came about in 3.5, but may be thinking of the ASP.NET AJAX implementation instead of jQuery's. See: Jquery's Ajax Property For Asp.Net 2.0, specifically:
You need to add this attribute to your webserver class
[System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
and this attribute to your functions
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
2.) You may want to check to see if the version of jQuery AJAX you are using is compatible with ASP.NET 2.0. I remember there being an issue there and needing to use older versions of jQuery (like 1.3) See: http://forum.jquery.com/topic/jquery-ajax-not-working-for-asp-net-2-0-7-5-2011
3.) This may be a long shot but is your page called Chat.aspx, or chat.aspx? Javascript capitalization matters (O;
Long shots, all of them, so good luck (:
[EDIT] Was just rereading the question and another idea popped in: Is the button from your .ASPX page? The reason I ask is because it's possible that when it's getting rendered on the page your button is no longer 'ID="btnSend"' but instead 'ID="ctl_btnSend_0897234h15807"' or so. If you have attached your jQuery to find '#btnSend' there's a chance that it's not the same ID in the DOM anymore.
Hoping that helps![/EDIT]

ASP.NET: Web Service or WCF for simple ajax call?

I just want to simply call a method on my web service via ajax and have it return a value.
Should I use "WCF Service" , "AJAX-Enabled WCF Service" , or "Web Service"
Which is the easiest?
Use a generic HTTP handler instead. They are simpler to code.
You should use Ajax-Enabled WCF service. I don't remember the name exactly but it should be marked with an attribute to be accessible from JS.
You should never use the "Web Service" template unless you're maintaining existing code and can't change.
If you are just calling a single method use ScriptMethod
You can code it inline with the page that it is used on.
http://www.asp.net/ajax/tutorials/understanding-asp-net-ajax-web-services
Using the ScriptMethod Attribute
The ScriptService attribute is the
only ASP.NET AJAX attribute that has
to be defined in a .NET Web Service in
order for it to be used by ASP.NET
AJAX pages. However, another attribute
named ScriptMethod can also be applied
directly to Web Methods in a service.
ScriptMethod defines three properties
including UseHttpGet, ResponseFormat
and XmlSerializeString. Changing the
values of these properties can be
useful in cases where the type of
request accepted by a Web Method needs
to be changed to GET, when a Web
Method needs to return raw XML data in
the form of an XmlDocument or
XmlElement object or when data
returned from a service should always
be serialized as XML instead of JSON.
The UseHttpGet property can be used
when a Web Method should accept GET
requests as opposed to POST requests.
Requests are sent using a URL with Web
Method input parameters converted to
QueryString parameters. The UseHttpGet
property defaults to false and should
only be set to true when operations
are known to be safe and when
sensitive data is not passed to a Web
Service. Listing 6 shows an example of
using the ScriptMethod attribute with
the UseHttpGet property.
If those are your only options, I've found the AJAX-Enabled WCF Service to be the simplest to work with. It's still WCF, but it templates out for you the proper web.config setup and ditches the interface that the plain "WCF Service" template gives you. It seems to be the closest thing in the whole WCF mess to the old ASMX-style as far as being dirt simple to get going.
Just as another alternative, if you happen to be able to use ASP.NET MVC in your webforms project and just need this for an ajax call, you could skip the web service hoopla altogether and create a simple JSON result for your AJAX call like so:
// put this method in a controller
public JsonResult AjaxJsonTest(string who) {
var result = new {
Success = true,
Message="Hello, " + (who ?? "world!")
};
return Json(result, JsonRequestBehavior.AllowGet);
}
And then you can call it from jQuery like this:
<script language="javascript" type="text/javascript">
function AjaxTestClick() {
$.ajax({
type: "POST",
url: '<%: Url.Action("AjaxJsonTest", "Test") %>',
data: { who: 'whomever' },
success: function (resultData) {
if (resultData.Success) {
alert(resultData.Message);
}
else {
alert('Ajax call failed.');
}
}
});
}
</script>
Tons of options - pick what suits your situation best.

Help with using jQuery with ASP.NET MVC

My app has a "Show all comments" similar to the one in Facebook. When the user clicks on the "show all" link, I need to update my list which initially has upto 4 comments with all comments. I'll show some code first and then ask some questions:
jQuery:
ShowAllComments = function (threadId) {
$.ajax({
type: "POST",
url: "/Home/GetComments",
data: { 'threadId': threadId },
dataType: "json",
success: function (result) {
alert(result);
},
error: function (error) {
alert(error);
}
});
};
Home Controller:
// GET: /GetComments
[HttpPost]
public JsonResult GetComments(int threadId)
{
var comments = repository.GetComments(threadId).ToList();
return Json(comments );
}
Questions:
When I tried GET instead of POST, I got this error: "This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet." Is POST usually recommended instead of GET when making these ajax requests? If not, how do I get it to work with GET? Where do I set JsonRequestBehavior to AllowGet?
After changing it to POST, I now get this error: A circular reference was detected while serializing an object of type 'Models.Thread'. I'm using Entity Framework 4, and I've read that adding a [scriptignore] attribute on the navigation property would resolve this, so I added a partial class of the entity with the property, it said "property is already defined". How do I then deal with this because I can't directly modify the code generated by EF4.
Set in the return Json. I would just use post, but if you want to make it hard on your self, use get.
public JsonResult blah()
{
return Json("obj", JsonRequestBehavior.AllowGet);
}
It is true when most ORM objects get serialized the serialization tries to searlize the hidden goodies the ORM needs, AND (sounds like your case) all of the lazy load stuff... this causes bad mojo. Can I throw a suggestion out? Why not let MVC do what its good at and generate the view for you? You could just use the jQuery .load and use a view.
Answers:
try return Json(comments, JsonRequestBehavior.AllowGet); There are good reasons for the default behavior though.
for anything going down the wire, you are going to really want to create a very simple view model object rather than sending your domain entity down the wire. Lots of fancy things happen in the EntityFramework that don't work with serialization as you are finding out.

How to get variables from JavaScript to ASP.NET (MVC)

I'm using ASP.NET MVC (I'm really new to both asp.net and the asp.net mvc type projects, but trying hard to learn).
I've set up MVC with a controller so that it runs a C#.net method which;
queries an mssql db
converts it to json
returns the json string
It's called from the javascript by requesting an url with a parameter. But what I need now is for the C# part to read two integer variables from the javascript. What would be the best way to do that, and does anyone have any good examples/code that I could look at?
It would be extremely helpful. Especially if there are smart ways of doing it with jquery / asp.net (mvc)
In your controller:
public JsonResult GetPony(string Name, string Color) {
return Json(new Pony(Name, Color), JsonRequestBehavior.AllowGet);
}
In your javascript:
$.get("/Controller/GetPony", {
Name: "foo",
Color: "bar"
});
jQuery will take care of moving stuff from the object into the querystring and MVC will take care of moving stuff from the query string into the call to your action.
To do that you need to send it as part of the ajax request. C# can't read your javascript, it can only read the request parameters.
If you're using jQuery, a request might look like this:
$.ajax({
url:"/products/detail",
type: "get", (or post, etc)
dataType: "json",
data: {productId: 55, culture:"en-US"},
success: your_success_callback,
error: function(e) { alert("An error occurred! " + e); }
});
The line that is interesting there is the data setting. It will serialize the data into name=val&name=val and send it to the server. If the type is set to GET then that will be appended to the querystring on the URL. If it's set to POST, then it will be embedded as part of the request.
The server portion doesn't care which. It can retrieve it like this:
public class ProductsController : Controller
{
public ActionResult Detail(int productId, string culture)
{
//your logic here
}
}

Categories