I have a web method that i am trying to call from jquery ajax but it is not getting invoked.
In firebug When i saw the response i get,
<title>Unknown web method MyMethod.<br>Parameter name: methodName</title>
error.I am not able to get the reason why this error is coming when that method is available at the server side..
Here is my client side code..
$("#excel").on("click", function (e) {
e.preventDefault();
var img = "image";
$.ajax({
type: "POST",
url: "Default.aspx/MyMethod",
data: JSON.stringify({ imageData: img }),
contentType: "application/json; charset=utf-8"
}).done(function (o) {
console.log(["Response:", o]);
});
});
And here is my server side code..
[WebMethod()]
public static void MyMethod(string imageData)
{
string fileNameWitPath = "D:/Kabir/custom_name.png";
using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(imageData);//convert from base64
bw.Write(data);
bw.Close();
}
}
}
Please help me to solve this issue as i am completely struck into this.
Thanks in advance..
Using this worked for me System.Web.Services.WebMethod
Try this
[System.Web.Services.WebMethod]
public static void MyMethod(string imageData)
{
}
System.Web.Services.WebMethod()
Initializes a new instance of the System.Web.Services.WebMethodAttribute class
System.Web.Services.WebMethod
Adding this attribute to a method within an XML Web service created using ASP.NET makes the method callable from remote Web clients
If the above doesn't works, make sure that the url you are passing is correct. And still if it doesn't works Check this out
This did worked on my system
Default.aspx
<form id="form1" runat="server">
<div id="excel">
Here</div>
</form>
<script type="text/javascript">
$("#excel").on("click", function (e) {
e.preventDefault();
var img = "image";
$.ajax({
type: "POST",
url: "Default.aspx/MyMethod",
data: JSON.stringify({ imageData: "Hello" }),
contentType: "application/json; charset=utf-8"
}).done(function (o) {
console.log(["Response:", o]);
});
});
</script>
Default.aspx.cs
[System.Web.Services.WebMethod]
public static string MyMethod(string imageData)
{
return imageData;
}
If you're looking for an answer about VB.net, you need to make your function Public Shared. I just ran into this issue myself.
Related
I am teaching myself how to program and I am having a hard time identifying an issue with my most recent experiment. The following is within the context of an 'ASP.NET Web Application (.NetFramework) C#' and MVC architecture.
I am attempting to post data from a html form to a c# controller method using a JavaScript function.
The JavaScript function invokes the controller method; however, the string passed to the method always has a null value. (I know that the new 'Organisation' instance is successfully created, as new instances appear with an ID in my database yet with a null name - as per my model).
I have searched similar questions and tested contentType: application/json; charset=utf-8 also; however, my issue persists.
The error reads: System.ArgumentNullException: 'Value cannot be null. Parameter name: s' and occurs at var jsonDataParsed = JObject.Parse(jsonData); in my c# controller method.
I was hoping someone may be kind enough to help me :)
The form:
<form id="createOrganisationForm">
<label for="organisationName">Organisation name</label>
<input type="text" id="organisationName" />
<input type="submit" onclick="createOrganisation()" value="submit" />
</form>
The Javascript function:
function createOrganisation() {
var formData = {
"OrganisationName": $("#organisationName").val()
}
$.ajax({
url: '#Url.Action("CreateOrganisation", "Organisations")',
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: JSON.stringify(formData)
})
}
The c# method in a controller:
[HttpPost]
public void CreateOrganisation(string jsonData)
{
var jsonDataParsed = JObject.Parse(jsonData);
var organisationName = jsonDataParsed["OrganisationName"].ToString();
var organisation = new Organisation();
organisation.Name = organisationName;
db.Organisations.Add(organisation);
db.SaveChanges();
}
The model:
public class Organisation
{
public int OrganisationID { get; set; }
public string Name { get; set; }
}
Try this:
function createOrganisation() {
var formData = {
"OrganisationName": $("#organisationName").val()
}
$.ajax({
url: '#Url.Action("CreateOrganisation", "Organisations")',
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType: 'json',
data: {'formData': formData }
})
}
Thank you everyone for your help. Special thanks go to #Teemu for pointing me towards the final solution.
Below is a working solution; I hope this may help others with future issues.
Key changes:
name="organisationName" atrribute added to input
<input type="submit" edited to <button type="button"
"parameter=" added to data: in ajax request
["OrganisationName"] edited to ["organisationName"] in C# method
Please refer to #Teemu advice in the question's comment section for the rationale behind these changes.
The HTML form:
<form id="createOrganisationForm">
<label for="organisationName">Organisation name</label>
<input type="text" id="organisationName" name="organisationName" />
<button type="button" onclick="createOrganisation()">Submit</button>
</form>
The JavaScript function:
function createOrganisation() {
var formData = JSON.stringify({ organisationName: $("#organisationName").val()})
$.ajax({
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: "jsonData=" + formData,
url: '#Url.Action("CreateOrganisation", "Organisations")',
type: "POST"
})
}
Helpful note: the above script should be in the view file (not an external file) if you are using a razor #URL.Action
The c# controller method:
[HttpPost]
public void CreateOrganisation(string jsonData)
{
var jsonDataParsed = JObject.Parse(jsonData);
var organisationName = jsonDataParsed["organisationName"].ToString();
var organisation = new Organisation();
organisation.Name = organisationName;
db.Organisations.Add(organisation);
db.SaveChanges();
}
Im working with the model view/Controller, so im trying to keep files in different folders like this
Im trying to call a c# class on the Business folder from the Boleta proyect with ajax within a aspx like this.
$.ajax({
type: "POST",
url: "Business/SaveExpenses.cs/save",
data: JSON.stringify({ questions: questions}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
console.log(data);
},
error: function (data) {
alert("fail");
}
});
The c# file that im trying to call looks like this.
namespace Business
{
public class SaveExpenses
{
public string save(string foo)
{
string ret= "something";
return ret;
}
}
}
When the page is executed and goes through the ajax function it throws an error 404 not found.
Now my question is, how do I navigate the folders in asp.net? or the correct way of calling the function.
Im comming from a php environment and im pretty new to asp.net so i will gladly take any suggestions
This url is wrong:
url: "Business/SaveExpenses.cs/save"
The URL should refer to the actual route. For example:
public class BusinessController : Controller
{
// GET
public ActionResult Index()
{
return View();
}
public string Save()
{
string ret= "something";
return ret;
}
Then your URL would be Business/Save(subject to RouteConfig etc considerations).
In Boleta project add the namespace of business
using Business;
then create one action in controller into Boleta Project
public JsonResult Save(param)
{
SaveExpenses se = new SaveExpenses();
var result= se.Save(param);
return json(result);
}
and call save() action through ajax
look into Adding a Web API Controller. basically, your ajax call will hit a http endpoint in which you'll execute your server side logic there.
The following is just a generic pattern - you'll need to implement a bit more plumbing to get this functional...
$.ajax({
type: 'POST',
url: '/Business/Expenses', // http route
// [...]
});
[RoutePrefix("Business")]
public class ExpensesController : ApiController
{
[HttpPost]
public IHttpActionResult Save([FromBody] string questions)
{
// do stuff
return Ok("something");
}
}
I'm trying to use ajax with post method but it keep poping me this error
An attempt was made to call the method \u0027SendEmail\u0027 using a GET request, which is not allowed
Here is the js
var obj = { name: name, company: company, country: country, email: email, msg: Msg }
var json = JSON.stringify(obj);
$.ajax({
method: "POST",
url: "ContactUs.aspx/SendEmail",
contentType: "application/json; charset=UTF-8",
data: json,
dataType:"json",
success: function (data) {
var a = 3;
},
error:function(a,b){
var a = 43;
}
})
and here is the server side on c#
[WebMethod]
public static void SendEmail(string name, string company, string country, string email, string msg)
{
}
Thanks in advance!
You should follow this way:
Your backend method which you already decorated with [WebMethod] and added a reference of using System.Web.Services;, I've changed the method to return something so it can be verified whether it works or not.
[WebMethod]
public static String sendEmail(string param)
{
return "Your String";
}
within your .aspx page, add scriptManager for enabling client side calling to your code behind methods
<asp:ScriptManager ID="scriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
Finally within your JQuery script, call the method like this:
$(document).ready(function () {
PageMethods.sendEmail("", onSuccess);
function onSuccess(response)
{
alert(response);
}});
Hope it helps!
Try to use [HttpPost] instead of [WebMethod] and remove static.
Is it a REST API or MVC?
I am quite new to JQuery and I was trying to do some asynchronous multipart form uploading. The form consist of few data fields and a file type. I have set up the server side code (Spring) like this:
#RequestMapping(method = RequestMethod.POST)
public #ResponseBody
Upload multipleSave(MultipartHttpServletRequest request)
{
Upload upload = new Upload();
Iterator<String> iterator = request.getFileNames();
while (iterator.hasNext())
{
MultipartFile file = request.getFile(iterator.next());
try
{
System.out.println(MessageFormat.format("File Length: {0}", Arrays.toString(file.getBytes())));
System.out.println("File Type: " + file.getContentType());
upload.setContent(file.getBytes());
upload.setDocId(id++);
upload.setError(null);
upload.setName(file.getName());
upload.setSize(file.getSize());
fileList.put(upload.getDocId().toString(), upload);
} catch (Exception e)
{
System.out.println("Error occurred: " + e);
upload.setError("500: Something went wrong!");
}
}
return upload;
}
and client side code like this:
function processFileUpload()
{
console.log("fileupload clicked");
var formData = new FormData();
formData.append("file", files[0]);
$.ajax({dataType: 'json',
url: "/SpringJqueryFileUpload/upload",
data: formData,
type: "POST",
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function (result) {
alert('success' + JSON.stringify(result));
},
error: function (result) {
alert('error' + JSON.stringify(result));
}
});
}
When I do submit, the server responds with this:
java.lang.IllegalArgumentException: No converter found for return value of type: class com.upload.model.Upload
I am wondering with error. Could I be missing something here??
I would try changing your annotation to:
#RequestMapping(method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
And make sure you have Jackson (which Spring uses for JSON serialization) properly on your path. Also, make sure your Upload class is serializable, e.g. is not private or anything like that. If it is just a normal Java bean type class it should be fine.
Lastly, if that doesn't work you can turn on Spring debug logs with something like:
log4j.category.org.springframework.web=ALL
in your log4j.properties file.
I tried to use TokenInput Jquery for multiple value autocomplete where it requires the JSON response as input data
http://loopj.com/jquery-tokeninput/
I am using ASPX page as source
<script type="text/javascript" >
$(document).ready(function() {
$("#txtTest").tokenInput("Complete.aspx", {
theme: "facebook"
});
});
</script>
Edited From Here
Question: How to provide the JSON data from a aspx page in the desired format as i have datatable with values according to Querystring from Complete.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request.QueryString["q"]))
{
string json = "[{\"Id\":\"1\",\"name\": \"Test 1\"},{\"Id\":\"2\",\"name\": \"Test 2\"}]";
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();
}
}
Any help will be appreciated.
Alternative to the WCF, you can create WebMethod in .aspx.
[WebMethod]
public static string Info()
{
JavaScriptSerializer js = new JavaScriptSerializer();
string result = js.Serialize(new string[] { "one", "two", "three" });
return result;
}
and request this WebMethod via Ajax call.
<script type="text/javascript">
$(function () {
$("#button1").click(function () {
$.ajax({
url: "Default.aspx/Info",
data: "{}",
contentType: "application/json",
success: function (data) {
alert(data.d);
},
type: "post",
dataType : "json"
});
});
});
</script>
EDIT:
Code-behind - Page_Load handler (JsonPage.aspx)
string json = "[{\"name\":\"Pratik\"},{\"name\": \"Parth\"}]";
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();
and request the JsonPage.aspx via TokenInput jQuery. (Sample.aspx & JsonPage.aspx are in same folder)
<script type="text/javascript">
$(function () {
$("#txt1").tokenInput("JsonPage.aspx");
});
</script>
<body>
<input type="text" id="txt1"/>
</body>
You should take a look at WCF. WCF has native support for returning JSON and you don't have to worry about string concatenation or HTTP content types.