Executing a C# method by calling it from client-side by ajax - c#

I'm trying to execute a server side method using this technique:
Javascript Ajax function
function storeLocal(brand, type) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{brand:'" + brand + "'}",
url: "Jquery Site.Master/storeLocal",
datatype: "json",
success: OnSuccess(brand),
});
}
function OnSuccess(brand) {
alert(brand);
}
C# method:
[WebMethod]
public static object storeLocal(string brand)
{
HttpContext.Current.Session.Add("Brand", brand);
}
line of code to execute is:
<li>
<a class="strong" onclick="storeLocal('petzl','harness')" href="About.aspx">Harnesses</a>
</li>
but its not executing correctly is there any particular error in my code?
reasone i am using this method is because i want to have a dynamic menu for a small project and wish to store in session what specific "li" did a user select in session so that i can load the content in the redirected page.
Thanks alot
Adrian

There is no return in your method that is might be the poblem, you method should be like as below
[WebMethod]
public static object storeLocal(string brand)
{
HttpContext.Current.Session.Add("Brand", brand);
return "value" +brand;
}

There are a couple of errors I can see with your ajax request:
The url parameter value isn't a proper URL.
Your not assigning your OnSuccess method correctly.
Try changing it to:
function storeLocal(brand, type) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{brand:'" + brand + "'}",
url: "ProperSiteUrl/storeLocal",
datatype: "json",
success: OnSuccess,
});
}
And you aren't returning anything from your storeLocal web method. Try changing it to:
[WebMethod]
public static object storeLocal(string brand)
{
HttpContext.Current.Session.Add("Brand", brand);
return ...;
}
Also, your sending JSON to the server, however, for a single parameter it you might find it easier just to send it as key/value pair e.g.
...
data: "brand=" + brand
...

i am not sure if your code is right! you have given both href and onclick and the page might navigate to about.aspx even before the onclick ajax event is completed.
try to remove the href or put the onclick event inside a href='javascript:storelocal()' and return the value from webmethod.
keep a breakpoint in the webmethod and see if the content is getting passed to the webmethod or not.

The url and success doens't look good.
1 - Within the ajax call you don't pass a argument to the success function. it will be returned something by the webmethod specified in c#.
you specify data in the data propriety, and that is used as the arguments passed to the webmethod.
2 - You can't call the webmethod using you master page, it has to be specified in the page that you are working. the aspx file not the master.
The page inherits from master, but it's not the master. Is a page with specification of the master page file.
Try this to identify errors, this for seeing what is returned
error: function (error) {
alert(JSON.stringify(error));
}

Related

Ajax call to MVC controllers

I'm trying to pass some data with ajax call to a c# mvc controller. Even though the task should be straight forward, I am unable to get the mvc controller to read the data I'm passing through the ajax call....
I've implemented the following code within my MVC controller
[HttpPost]
public string tt(string o)
{
return o;
}
[HttpPost]
public string tt2(string o)
{
return "lala";
}
And I'm triggering the following ajax calls from the browser
$.ajax({
url: "/Home/tt2",
type: "POST",
contentType: "application/json;",
data: JSON.stringify({ o: 'asdas'}),
success: function(e){console.log(e+' correct');},
error: function(e){console.log(e+' incorrect');}
});
$.ajax({
url: "/Home/tt",
type: "POST",
contentType: "application/json;",
data: JSON.stringify({ o: 'asdas'}),
success: function(e){console.log(e+' correct');},
error: function(e){console.log(e+' incorrect');}
});
As a result when running the first ajax call the result is
lala correct
And for the second ajax call, the result is
undefined correct
In the mean time these are some stuff I tried
Adding dataType: "json", to the ajax call
Changing the string data from {o: 'asdas'} to 'asdas'
Removing the JSON.stringify
Adding the charset=utf-8 to the contentType
Changing the ajax call type and MVC controller method from POST to GET to PUT
Changing the MVC controller method parameter from string to int
Removing the error method from the ajax call
Changing the data from data: {o: 'asdas'} to data: {"o":"asdas"}
Changing the data from data: {"o":"asdas"} to data: JSON.stringify({"o":"asdas"})
I know that simple string or int can be passed through the URL as query strings but it would be an issue when passing a list of objects..
Something aside is that the call is being done correctly to the URL because when I set a breakpoint within the called method, it does get triggered but the parameter always is null..
Any thoughts on how to make ajax call work?
try:
[HttpPost]
public string tt([FromBody]string o)
{
return o;
}
Your request should be like this:
$.ajax({
url: '#Url.Action("tt", "Home")',
data: {
"o": "asdasdas"
},
cache: false,
type: "POST",
success: function (response) {
},
error: function (xhr) {
}
});

MVC Send list through AJAX

Okay, I've seen tons of questions posted regarding this question, but none of the answers has actually worked for me, here's my AJAX:
$.ajax({
url: "/FilterSessions/GetFilterSession",
type: "GET",
dataType: "json",
data: jsonFilters,
traditional: true,
success: function (response) {
//Haha, it's never entering here. not really.
}
});
var "jsonFilters" contains an array with the following data:
[0] = { Path: "Test", Name: "More testing", Value: "Test Value" },
[1] = { Path: "Test", Name: "More testing", Value: "Test Value" }
And this is my controller:
public ActionResult GetFilterSession(List<FilterSessionModel> jsonFilters)
{
//Do things
return Json(false, JsonRequestBehavior.AllowGet);
}
jsonFilters always remains null... I have also tried adding contentType: "application/json; charset=utf-8" to the AJAX call... but that didn't really do anything
Finally, the class FilterSessionModel is structured as follows:
public class FilterSessionModel
{
public string Path { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
Any ideas as to what I might be missing or what might be happening?
Things I've tried so far:
Setting "traditional: true", setting "contentType", using JSON.stringify and attempting to accept a string in the MVC Controller (no-go)
UPDATE: Thanks to the answer below I realized that what was missing was to send over the data with the param Id like so:
data: "{param1ID:"+ param1Val+"}"
I would try switching out the type on your action.
List<FilterSessionModel>
Pretty sure the above is not going to work, I would try something like Object.
Or possibly a string that I would then use newton json dll to push into your List of Class.
The problem boils down to your action being unable to figure out the type, assuming you are checking your data prior to the ajax get being called.
**Update due to more info. Add in the error portion and view those vars on return from your controller, also fire up fiddler and watch what your are getting for http numbers.
$.ajax({
type: "POST",
url: "Servicename.asmx/DoSomeCalculation",
data: "{param1ID:"+ param1Val+"}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
UseReturnedData(msg.d);
},
error: function(x, t, m, b) {
//Look at the vars above to see what is in them.
}
});
I think what you are looking for is answered here:
Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax
First off I'm making the assumption that your $.ajax is for JQuery and not some other Javascript framework. Please correct me if that's wrong.
ASP.NET MVC can actually do what you are asking it to (resolve data sent via AJAX to a List<FilterSessionModel>, but it seems to have a difficult time doing it via a GET request. It would help to know which version of ASP.NET MVC you are using, as more is required to get this working on the older versions. However, what I'm suggesting should work on MVC 3 or 4.
When you send AJAX via JQuery using a GET request and passing it a JavaScript array, this is what you are sending to the server:
http://localhost:50195/FilterSessions/GetFilterSession?undefined=&undefined=
It's no wonder the model is null because no data is actually being sent.
I believe ASP.NET can accept objects (and even arrays of objects) like this, but it won't do so with it formatted as JSON (like via JSON.stringify) as that just results in the following request:
http://localhost:50195/FilterSessions/GetFilterSession?[{%22Path%22:%22Test%22,%22Name%22:%22TestName%22,%22Value%22:%22Testing%22},{%22Path%22:%22Test%22,%22Name%22:%22TestName%22,%22Value%22:%22Testing%22}]
The way you probably want to do this is with a POST request. ASP.NET MVC will actually accept a JSON string as POST data and will decode it and resolve the model properly. Your AJAX code works fine with a couple modifications:
$.ajax({
url: "/FilterSessions/GetFilterSession",
type: "POST", //Changed to POST
dataType: "json",
data: JSON.stringify(jsonFilters), //Pack data in a JSON package.
contentType: "application/json; charset=utf-8", //Added so ASP recognized JSON
traditional: true,
success: function (response) {
alert('Success!');
}
});
The controller you posted should recognize POST data already, but in case it doesn't, a simple [HttpPost] attribute is all you need:
[HttpPost]
public ActionResult GetFilterSession(List<FilterSessionModel> jsonFilters)
{
//Do things
return Json(false, JsonRequestBehavior.AllowGet);
}
javascript or ajax call never type cast the object. . .you need to set type of the controller side parameter either string or List else you can also set the Object type. . If you modified codein that way.. .Your code definitely work !!!
$.ajax({
url: "/FilterSessions/GetFilterSession",
type: "GET",
dataType: "json",
data:JSON.stringify({ 'jsonFilters': jsonFilters}),
contentType: 'application/json; charset=utf-8',
success: function (response) {
//Do your action
}
});

Getting error when doing a jquery ajax function to a aspx page

I want to send data using ajax from jQuery to c# (note: I'm sending request to the same page).
I am following this tutorial http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/.
NOTE: This is a asp.net 3.5 on SharePoint 2010 webpart solution.
This is my jquery code:
$.ajax({
type: "POST",
url: getURLWithoutQuery() + "/saveOrder",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
// return the url of the current page without any query parameters
function getURLWithoutQuery() {
return location.protocol + '//' + location.host + location.pathname;
}
and in c#, the main file is PDFLibraryUserControl.ascx.cs. This is the one that has the Page_Load function.
However I have another class file called SaveStructure.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.Services;
namespace PDFLibrary.PDFLibrary
{
public partial class SaveStructure : Page
{
[WebMethod]
public static int saveOrder()
{
return 1234;
}
}
}
I expect to get an alert saying 1234, but instead I get this:
Does it have something to do with the function saveOrder being on another file than the main one? Or maybe my URL is not correct? I don't want to hardcode the URL in it, because the current page is the aspx page and also contains the jQuery code to send the POST (to the same page).
Does anyone know what's wrong and can fix this?
Putting page methods inside of a user control is a bad idea, because the biggest problem is that user controls are not directly accessible via script (read: jQuery) like .aspx pages are. If you are constrained to only putting this logic in a user control, then my recommendation is create a web service (.asmx) that will perform the logic the page method was going to do. A web service is directly accessible via the jQuery .ajax() method, like this:
Code from myService.asmx:
[WebMethod]
public static int saveOrder()
{
return 1234;
}
Code in SharePoint .aspx page:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "myService.asmx/saveOrder",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: handleSuccess,
error: handleError
});
});
function handleSuccess(data, status) {
// Do something with successful data retrieval
}
function handleError(xmlRequest) {
// Do something with error
}
</script>

How to return value to AJAX from code behind? [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
How To Return Value From Code Behind To AJAX?
This is my AJAX code
$.ajax({
type: 'POST',
url: 'country_management.aspx/save',
cache: false,
data: "{'parameter':'paramValue'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d);
if (data.d == "error") {
$('.success_box').hide();
$('.error_box').show();
}
else {
$('#name').val('');
$('.error_box').hide();
$('.success_box').show();
}
}
});
Code Behind:
[WebMethod]
[ScriptMethod]
public static string save(string parameter)
{
string name = HttpContext.Current.Request.QueryString["name"].Trim();
return "error";
}
after writing the first line, return statement does not return anything to the AJAX.
Without knowing the context of the whole application is kind of difficult to answer your question. (Does name get supplied from elsewhere in the app, you could make use of a session?)
But what is stopping you from passing the name through in the ajax call? Rather than just sending through'parameter':'paramValue'.
You have to remember your query string is supposed to contain the parameter you're looking for. at the moment it's looking something like.
http://www.somesite.com/country_management.aspx/save?parameter=paramValue
when you actually need
e.g.
http://www.somesite.com/country_management.aspx/save?parameter=paramValue&name=newName
Javascript
$.ajax({
type: 'POST',
url: 'country_management.aspx/save',
data: { parameter:'paramValue', name: 'newName'},
success: function (data) {
//do something with the response
}
});
Codebehind
[WebMethod]
[ScriptMethod]
public static string save(string parameter, string name)
{
PerformSave(name, parameter);
return "Data Saved!";
}
TIP
Try out this app. Fiddler. It's extremely useful when you're working with things like ajax calls etc. Actually any web development. :)
Because you didn't post any field or property "name"
If you do the ajax after clicked in a button inside form, data will be the form serialized.
Another thing is, why should you expect "name" var in query string, I don't see any url with aspx?name="any name"

Pass a parameter to server method using JavaScript

I have a public in my code behind page that takes a string.
I would like to call this method from javascript.
The parameter that I want to pass down is variable that changes from a ddl.
So I have something like this:
var value = document.getElementById('ddlContact').value;
<%=PopulateContactFields("value") %>
This passes down the word 'value' and not the data in value.
I can't figure out the proper syntax to pass down the data in value.
Thanks
As mentioned by others, trying to access C# code behind directly from javascript is impossible.
However, you can communicate with it indirectly.
I think your best shot is to use a combination of jQuery and the [WebMethod] attribute.
javascript function using jQuery to do an AJAX call:
function Search() {
var search = $('#<%= ddlContact.ClientId %>').val();
var options = {
type: "POST",
url: "Default.aspx/Hello",
data: "{'name' :'" + search + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
}
};
$.ajax(options);
}
Code behind:
public partial class _Default : System.Web.UI.Page
{
[WebMethod]
public void Hello(string name)
{
return "Hi " + name;
}
}
The code you are showing is executed server side when the HTML is generated. In other words it is executed BEFORE it hits the browser and your user had a chance to do anything with the page.
No matter what syntax you would use here the information you want cannot be accessed at this time - it does not exist yet.
The right approach here is to sent this information to the server either by posting the page or using AJAX and then, on the tail end of request/response cycle do your processing
Another option would be to do the processing client side using Javascript

Categories