Unable to call the webservice by passing parameters using jquery - javascript

I call the webservice using jquery, whenever i call, i get the error result only.
My server code:
[WebService(Namespace = "http://xxx.xample.org")]
[WebServiceBinding( Name ="XService", Namespace="http://xxx.xample.org/XService.asmx?")]
[System.Web.Script.Services.ScriptService]
public class AathiService : System.Web.Services.WebService
{
[WebMethod]
public string IsValidUser(string UserName , string Password)
{
// process
return result;
}
}
}
Then i call the service using jquery like this.. .
$("#okButton").click(function () {
// CALLING WEBSERVICE
var param = { UserName: 'xxxx', Password: 'xxxxx' };
$.ajax({ type: "POST", contentType: "application/json;charset=utf-8", data: JSON.stringify(param),
url: "http://xxx.xample.org/xService.asmx/IsValidUser", dataType: "json", async: true,
success: function () { alert("success"); }, error: function (xhr,msg) { alert(msg + " " + xhr.responseText); }
});
});
I am always get the error part. i doesn't know what i am done .

in your webmethod you are expecting a "string" as return type , but you call the ajax call with datatype JSON
this should solve your problem:
[WebMethod]
public JsonResult IsValidUser(string UserName , string Password)
{
// process
return Json(result);
}

Just change async: false. problem solved

Related

C# MVC pass parameters from View to Controller using dotnetfiddle

I am learning C# MVC using dotnetfiddle web to write code.
I have created a new project with the default code of dotnetfiddle for MVC type, but I want to display the question in the alert instead of the answer.
I want to know how to pass parameters to the controller from the view.
This is the ajax method:
$.ajax({
url: '#Url.RouteUrl(new{ action="GetAnswer", controller="Home"})',
data: JSON.stringify({Answer: '', Question: $('#Question').val()}),
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(resp) {
openAlert(resp.result);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
openAlert("ERROR: " + errorThrown);
}
});
And this is the controller method:
[HttpPost]
public JsonResult GetAnswer(string question)
{
int index = _rnd.Next(_db.Count);
var answer = _db[index];
return Json(new { result = question});
}
You can check and test the code here: dotnetfiddle (Edit: it will be a good answer if it works here)
These code changes will work for you. If you wanna verify check the fiddle. DotNetFiddle
Client side Changes
$.ajax({
url: '#Url.RouteUrl(new{ action="GetAnswer", controller="Home"})',
data: {"Answer": '', "Question": $('#Question').val()},
type: 'POST',
success: function(resp) {
openAlert(resp.Question);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
openAlert("ERROR: " + errorThrown);
}
});
Server Side Changes
[HttpPost]
public JsonResult GetAnswer(SampleViewModel model)
{
int index = _rnd.Next(_db.Count);
var answer = _db[index];
return Json(model);
}
This is the method I used to pass parameters to controller
First, assign the parameter you want to pass to a variable with the value from the
input id as stated in your dotnetfiddle
var questionParam = $("#Question").val();
Then for passing it to AJAX, I think your method is already correct, this is how I do it
$.ajax({
url: '/Home/GetAnswer?question=' + questionParam ,
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(resp) {
openAlert(resp.result);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
openAlert("ERROR: " + errorThrown);
}
});
This method works for me in my project, if the value is a string I think you don't need to stringify the value.
I'm still a beginner as well so maybe my method is wrong or not the best way to do it, I hope it helps you.
You are getting the value of the question in the action because your action has got a single parameter string question in there.
What you need to do is:
Send a json object from the view
In the action user a model with two properties (Answer and Question) to get the value sent by the view
Then in the action you decide what data you need to send to view
View:
Send JSON object to action:
JSON.stringify({Answer: '', Question: $('#Question').val()})
When you get the data returned from controller:
openAlert(resp.Answer);
Controller:
public JsonResult GetAnswer(MyQA model)
{
// model.Answer
// model.Question
// Your business logic goes here
return Json(new { result = model});
}
Here is the MyQA class:
public class MyQA
{
public string Answer { get; set; }
public string Question{ get; set; }
}
dotnetfiddle had a problem with this line: contentType: "application/json; charset=utf-8",
change script to :
$('.submit').click(function() {
if ($('form').valid()) {
$.ajax({
url: '#Url.Action("GetAnswer", "Home")',
data: {
Answer: '',
Question: $('#Question').val()
},
type: 'POST',
dataType: 'json',
success: function(resp) {
openAlert('Answer :' + resp.Answer + ' -----Question : ' + resp.Question);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
openAlert("ERROR: " + textStatus);
}
});
} else {
closeAlert();
}
});
change action GetAnswer to :
[HttpPost]
public JsonResult GetAnswer(string Answer,string Question)
{
int index = _rnd.Next(_db.Count);
var answer = _db[index];
return Json(new {Answer = answer,Question = Question});
}

AJAX post data is null when it reaches the ASP.NET Core 2.1.1 controller

I have a problem posting a value from java-script in my razor page to a controller. - the value received is always null.
I have seen similar questions being asked, but have not been able to find the right solution to the problem.
I get to a break point in the controller, (so the routing is okay) but the parameter value passed is always null, and not being the sharpest in java-script, I would like some tips from you folks.
I basically have the java-script below:
var clickButton = function (buttonId) {
$.ajax({
type: "POST",
async: false,
cache: false,
crossDomain: false,
contentType: "application/json; charset=utf-8",
url: "v1/buttons",
dataType: "json",
data: '{ buttonId:'+JSON.stringify( "buttonId" ) + '}',
success: function (result) {
//console.log("clickButton OK => " + result);
}, //success: function (result) {
timeout: 500 // 0.5 sec.
}); //$.ajax({
}//var clickButton = function(buttonNo) {
and the C# controller code below too:
[Route( "v1/[controller]" )]
public class ButtonsController : Controller
{
...
[HttpPost]
public IActionResult OnButtonClicked( string buttonId )
{
// buttonId = null !!!
...
I have a similar problem getting a boolean value across to another controller.
where the bool is always false.. i.e. the default value.
I am wondering if it is a security issue, with not allowing the post to contain data, when the user is unauthorized...
The problem was in the JSON, and I got the value through with this minor change, but it was hiding well.
var clickButton = function (buttonNo) {
console.log("clicked: " + buttonNo);
$.ajax({
type: "POST",
url: "v1/buttons/",
dataType: "json",
data: { "buttonId": buttonNo }, // < === this is where the problem was !!
success: function (result) {
}, //success: function (result) {
}); //$.ajax({
}//var clickButton = function(buttonNo) {
I've changed the controller to receive a string to id the button.
And it now looks like this:
[Route( "v1/[controller]" )]
public class ButtonsController : Controller
{
...
[HttpPost]
public IActionResult PostButtonClick( string buttonId ) {
// buttonId now has a value !!!
}
}

Error while calling Webapi in my asp.net project

This is my api code that return successfull json data while using get method
public Question[] Get() {
getQuestion obj = new AllDataAccess.getQuestion();
return obj.questionList().ToArray();
}
This is my post method data that accept the value and save in database
public void Post([FromBody] string question) {
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
This is the method that call my api
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'http://localhost:53893/api/values',
data: "{'question':'" + $("#submit").value + "'}",
dataType: 'json',
async: false,
success: function(data, status) {
console.log(status);
},
error: function(err) {
console.log(err);
}
});
Now the problem is when i post the data with one textbox value its give me a message in console that "nocontent" and record save in data base with null value
It seems that your ajax url is wrong. You should specify the action name (post). Also, use JSON.stringify to retrieve proper json from javascript object.
var postData = { question:$("#submit").val() };
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'http://localhost:53893/api/values/post',
data: JSON.stringify(postData),
dataType: 'json',
success: function (data,status) {
console.log(status);
},
error: function (err) {
console.log(err);
}
});
In the server side, you should create a model class for Post method;
public class PostInput
{
public string Question { get; set; }
}
And then Post method looks like;
[HttpPost]
public void Post([FromBody]PostInput input)
{
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
If you want to use FromBody, you can do so.
JavaScript
$.ajax({
type: "POST",
//default content-type, could be omitted
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
url: 'http://localhost:53893/api/values/post',
data: {'': $("#submit").val()}
});
API action
[HttpPost]
public void Post([FromBody]string question)
{
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
You had these issues.
Wrong content-type for your ajax call.
Data was not posted correctly.
val() should be used instead of .value.
API action should be decorated with [HttpPost].

Is it impossible to download file via AJAX call in ASP.NET MVC5?

I know it seems to be better to use normal call instead of AJAX call but for some reason i.e. displaying error message on modal dialog in case a problem during download, I need to download file by using an AJAX call in an MVC5 project. Here is what I did finally after lot of tries:
View:
Download
function downloadFile() {
$.ajax({
type: 'POST',
url: '/Experiment/GetFile',
data: '{id:' + 8 + '}', //For test purpose I used static id
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (returnValue) {
window.location = '/Experiment/GetFile?id=' + returnValue;
}
});
};
Controller:
In Controller, I have a method something like that, but I am really confused if I should do the same method for AJAX Post and success method or not.
[HttpPost]
public ActionResult GetFile(int id)
{
var dataContext = repository.FileAttachments.FirstOrDefault(m => m.Id == id);
if (dataContext == null)
{
return Json(new { success = true, returnValue = "8" });
}
else
{
return Json(new { success = false, message= "Error..." }, JsonRequestBehavior.AllowGet);
}
}
Is there a smart approach to perform this dosnload operation using AJAX call in ASP.NET MVC5?
You need to return file name or file path
Example "/file/download.doc"
And then you need to edit view page like follow
Download
<a href="" id="todownload" download>
function downloadFile() {
$.ajax({ type: 'POST', url: '/Experiment/GetFile', data: '{id:' + 8 + '}', //For test purpose I used static id
contentType: 'application/json; charset=utf-8', dataType: 'json',
success: function (returnValue)
$("#todownload").attr('href',returnValue);
$("#todownload").click();
}
});
};

Ajax query string not being posted to ASP.NET controller

I have this Ajax function:
UpdateFIConfig: function ($appForm) {
var valid = $appForm.valid();
//if not valid the validate plugin will take care of the errors
if (valid) {
$appForm.serialize();
$.ajax({
url: '/IdentifiConfig/DefaultConfiguration/UpdateFIConfig',
data: $appForm,
dataType: 'application/json',
cache: false,
type: 'POST',
success: function (data) {
if (data.Error) {
cc.jqUtils.openDialog(data.ErrorDescription, 'Error', 'OK', null, null, null);
} else {
window.location.href = '/IdentifiConfig/DefaultConfiguration';
}
}
});
}
},
Which serializes data sent from my view into a query string. I know the data is serialized correctly because I have viewed the string with console.log($appForm), and it's correct.
However, my controller never receives the query string. I have removed a lot of code, but this is basically what the controller function looks like:
[HttpPost]
public ActionResult UpdateFIConfig(string query)
{
NameValueCollection nvc = HttpUtility.ParseQueryString(query);
System.Diagnostics.Debug.WriteLine(nvc);
}
I receive a null pointer on the line which tries to parse the query string, and I don't know why. Any help?
i have the same thing ajax in my project the only different is i don't use dataType
but contentType: "application/json; charset=utf-8"
data: "{'query' : '" + $appForm + "'}"
This bit:
$appForm.serialize();
Returns a string that you're never using. serialize won't actually modify the form. You should assign it to a variable and pass that up instead:
var data = $appForm.serialize();
$.ajax({
url: '/IdentifiConfig/DefaultConfiguration/UpdateFIConfig',
data: data,
/* etc */
});
There is probably a better way, but I get around this annoyance by accepting an Object with a string property instead of just a string. So do something like:
[HttpPost]
public ActionResult UpdateFIConfig(MyTypeWithQry query)
{ ...
and
$.ajax({ url: '/IdentifiConfig/DefaultConfiguration/UpdateFIConfig',
data: { 'query' : $appForm },
dataType: 'application/json',
...

Categories

Resources