Ajax doesn't send any strings to the controller.
Here's my function:
$(function () {
$('#btnAnswer').click(function () {
var code = $('#Answer').val();
$.ajax({
url: '#Url.Action("CheckAnswer", "Home")',
type: "POST",
data: code ,
datatype: "text",
success: function (resultFromFunct) {
$("#resultsBox").append(resultFromFunct);
}
});
$('#Answer').val('');
});
});
Here's my controller:
[HttpPost]
public string CheckAnswer(string answer)/
{
game.LogUserAnswer(Request.Cookies["user"].Value, answer);
return String.Format("<strong>{0}</strong>: {1} <br>", Request.Cookies["user"].Value, game.UserGuess(answer));
}
Ajax is correctly get into CheckAnswer method but answer is always null. I've tried other examples from stack, for instance Asp.Net Mvc JQuery ajax input parameters are null but always get null result. Do you have any thoughts of the cause?
Change your request parameters to data: { answer: code } in your request. It probably can not match code to the parameter on your action.
$(function () {
$('#btnAnswer').click(function () {
var code = $('#Answer').val();
$.ajax({
url: '#Url.Action("CheckAnswer", "Home")',
type: "POST",
data: { answer: code },
datatype: "text",
success: function (resultFromFunct) {
$("#resultsBox").append(resultFromFunct);
}
});
$('#Answer').val('');
});
});
Related
I want to post data in the Mssql Database using Asp.netCore Api and Html Form. I have Added This script to post data.but All the values are coming null
Jquery script in Html File
<script type="text/javascript">
var valdata = $("#formData").serialize();
$(document).ready(function () {
$("#btnsubmit").click(function (e) {
let formData = {};
$("#formData").serializeArray().map((x) => { formData[x.name] = x.value; });
$.ajax({
url: "https://localhost:44389/Register",
contentType: "application/json; charset=utf-8",
type: 'POST',
dataType: 'json',
data: valdata,
success: function (data) {
alert(data);
},
failure: function (data) {
alert("Failure: " + data);
},
error: function (data) {
alert("Error: " + data);
}
});
});
});
</script>
.net Core Api
[HttpPost]
[Route("Register")]
public void RegisterExecute([FromBody]CustmRegistration Register)
{
try
{
userInterface.InsertCustomer(Register);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
but All the values are coming null
Where are these values null? my suggestion is to start debugging a bit more thoroughly.
Have you tried your api function trough postman or a tool likewise?
Settting breakpoints can be nice to look into your program's data at runtime.
if these values are null in your database it would be nice to see what userInterface.InsertCustomer(Register); does.
Once you know if your .net part is working start debugging your ajaxc call. take a look at the network section of the developer tools form the browser you are using.
If you have collected more data, people can help you more easelly.
1.When you use .serialize(), it generates the data in a query string format which needs to be sent using the default contentType which is application/x-www-form-urlencoded; charset=UTF-8, not as JSON. Either remove the contentType option or specify contentType: application/x-www-form-urlencoded; charset=UTF-8 can work.
2.Also you need move the serialize method into onclick event.
3.Be sure change [FromBody] to [FromForm].
Here is a whole working demo:
View:
#model CustmRegistration
<form id="formData">
<!--more code-->
<input type="button" id="btnsubmit"value="create" />
</form>
#section Scripts
{
<script type="text/javascript">
$(document).ready(function () {
$("#btnsubmit").click(function (e) {
var valdata = $("#formData").serialize(); //move to here...
$.ajax({
url: "/home/Register",
//contentType: "application/json; charset=utf-8",
type: 'POST',
dataType: 'json',
data: valdata,
success: function (data) {
alert(data);
},
failure: function (data) {
alert("Failure: " + data);
},
error: function (data) {
alert("Error: " + data);
}
});
});
});
</script>
}
Controller:
[HttpPost]
[Route("Register")]
public void RegisterExecute([FromForm]CustmRegistration Register)
{ //...}
I have the following jquery function which is sending data to a controller:
function bound(e) {
var ele = document.getElementsByClassName("e-grid")[0]
ele.addEventListener('click', function (e) {
if (e.target.classList.contains('e-up')) {
var grid = document.getElementById('FlatGrid').ej2_instances[0]; //Grid Instance
var rowObj = grid.getRowObjectFromUID(ej.base.closest(e.target, '.e-row').getAttribute('data-uid'));
var data = rowObj.data;
//alert(JSON.stringify(data));
var code = data.ClientCode;
$.ajax({
type: "POST",
url: "/Client/ShowClient",
data: { "ClientCode": code }, //First item has latest ID
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});
}
});
}
And my controller method:
[HttpPost]
public ActionResult ShowClient(string ClientCode)
{
if (ClientCode == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
*action*
}
However I am getting a 500 (Internal Server Error) error for this. Any idea what I am missing cause my method is not being hit at all.
And I can see that var code does have the correct string value.
Remove commas from the parameter name "ClientCode" and contentType and will be work
$.ajax({
type: "POST",
url: "/Client/ShowClient",
data: { ClientCode: code }, //First item has latest ID
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});
The comments have provided you with a combination of suggestions that when put together will give you the desired behavior.
First, you can build the URL in teh view using #Url.Action
url: '#(Url.Action("ShowClient","Client"))',
Next, the object model is not being built correctly
data: { ClientCode: code },
Note the last of quotes around the key.
And finally remove the JSON content type.
Which results to portion of code.
$.ajax({
type: "POST",
url: '#(Url.Action("ShowClient","Client"))',
data: { ClientCode: code },
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});
Change the url to this:
url: "../Client/ShowClient"
I am passing an array from view to controller using Ajax but, on action, the array shows empty.
This is my code:
View
$("#btn").click(function () {
debugger
arry = [];
$.ajax({
type: "Post",
url: "/Main/CheckBoxes",
data: { Values: arr["48","47","46"] },
success: function () {
alert("array: " + arry.join(', '));
},
error: function () {
alert("error");
}
})
});
Action
public ActionResult array(string[] Values)
{
for (int id = 0; id < Values.Length; id++)
{
string newID = Values[id];
}
return View();
}
jQuery.ajaxSettings.traditional = true;
$("#btn").click(function () {
debugger
arry = [];
$.ajax({
type: "Post",
url: "/Main/CheckBoxes",
data: { Values:["48","47","46"]},//just edit this line
success: function () {
alert("array: " + arry.join(', '));
},
error: function () {
alert("error");
}
})
});
Your code has some issues regarding how you are sending the data! What is your expectation when you execute this expression arr["48","47","46"] ????? That is going to give you undefined and that is what you are trying to send!
There are two ways to fix your code. You can send the array in the request body. For this, you need create a JSON string from the array and send that as the data property while explicitly specifying the request content-type header value as "application/json". You may use the JSON.stringify method to get the JSON string of your js array.
Also, make sure you are making the call to the correct action method. In your question you shared the array action method code, but in your client side script you were trying to call a different action method(`Checkboxes)!
This should work.
var arry = ["48", "47", "46"];
var url = "#Url.Action("array", "Main")"; // Update your real url here
// If your script is inside the razor view, you can us Url.Action (c#) method
$.ajax({
type: "Post",
url: url ,
data: JSON.stringify(arry),
contentType: "application/json",
success: function(r) {
alert("Success");
console.log(r);
},
error: function() {
alert("error");
}
});
Another option is to send a javascript object with Values property (which has the array as the value of it) as the data property value of the $.ajax call. Now the request content-type header will be application/x-www-form-urlencoded; and the array will be sent as FormData in the request.
var arry = ["48", "47", "46"];
$.ajax({
type: "Post",
url: "/Main/array",
data: { Values: arry },
success: function(r) {
console.log(r);
},
error: function() {
alert("error");
}
});
I'm trying to call the jQuery function $.get() to make a call to my WebMethod but it's only hitting the Page_Load event in the code behind. I can see the request being sent out in firebug to /admin/manage-users.aspx/deleteUser?u=user1 but it never hits the WebMethod.
jquery
$('#delete').each(function () {
$(this).click(function () {
var userName = $(this).closest('tr').find('span.userName').text();
$.get('/admin/manage-users.aspx/deleteUser', { u: userName });
});
});
aspx.cs
[WebMethod]
public void deleteUser() {
string userName = Request.QueryString["u"];
if(!string.IsNullOrEmpty(userName)) {
if(Membership.DeleteUser(userName))
Response.Redirect(Request.Url.ToString());
}
}
SOLUTION
I gave credit to bugz below because he pointed me in the right direction.
In order for your [WebMethod] to work your method within the aspx has to be static
Here is a link for more information
More Information
$.ajax({
type: "POST",
url: "'/admin/manage-users.aspx/deleteUser'",
data: "{'userName ' : '" + userName + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
//do something on success
},
error: function(ex) {
//do something on failure
}
});
Also on success if you are returning data or a variable make sure you use data.d for some reason when using jquery/ajax microsoft wants the .d at the end of the variable. This took me time to figure out.
Try this Im guessing when you debug the deleteUser Method never gets called.
var jqxhr = $.get("admin/manage-users.aspx/deleteUser", { userName: userName } function() {
alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
I'm trying to use Ajax of jQuery, I have this code below and although I get no error in firebug it's not working, It seems the function in code behind doesn't get any params.
(document).ready(function () {
$("#S1").click(function
() {
$("#t1").toggle("fast");
$("#P1").toggle("fast");
$("#S1").css("background-color", "White");
var ID = $("#HiddenField1").attr("Value");
var params = { 'Key': ID };
$.ajax({
type: "POST",
url: "viewMessages.aspx/readen",
data: params,
dataType: "json"
});
});
});
and here is the code behind
[WebMethod(EnableSession = false)]
public static void readen(string Key)
{
DBController db = new DBController();
db.ReadenMes(Convert.ToInt32(Key));
}
the code below work but since I wanna use it in IE 6 I have to use the code above.
$(document).ready(function () {
$("#S2").click(function
() {
$("#t2").toggle("fast");
$("#P2").toggle("fast");
$("#S2").css("background-color","White");
var ID = $("#HiddenField2").attr("Value");
var params = new Object();
params.Key = ID;
var myJSONText = JSON.stringify(params);
$.ajax({
type: "POST",
url: "viewMessages.aspx/readen",
data: myJSONText,
contentType: "application/json",
dataType: "json"
});
});
});
where do you think i'm doing wrong?
3 mistakes to avoid when using jQuery with ASP.NET AJAX
$(document).ready(function () {
$("#S1").click(function
() {
$("#t1").toggle("fast");
$("#P1").toggle("fast");
$("#S1").css("background-color", "White");
var ID = $("#HiddenField1").val();
var params = "{ 'Key':'" + ID + "'}"; //changes here
$.ajax({
type: "POST",
url: "viewMessages.aspx/readen",
data: params,
dataType: "json",
contentType: "application/json; charset=utf-8"
});
});
});
If your issue only is that IE6 has no JSON.stringify method, than you can use json2.js from Douglas Crockford and then your second sample should work as expected in IE6 too.
$(function () {
$("#S2").click(function
$("#t2").toggle("fast");
$("#P2").toggle("fast");
$("#S2").css("background-color","White");
var ID = $("#HiddenField2").attr("Value");
var myJSONText = JSON.stringify({ Key: ID });
$.ajax({
type: "POST",
url: "viewMessages.aspx/readen",
data: myJSONText,
contentType: "application/json",
dataType: "json"
});
});
});
Another approach is do not use 'json' datatype, and then params should be serialized as regular query string.
$(function () {
$("#S2").click(function
$("#t2").toggle("fast");
$("#P2").toggle("fast");
$("#S2").css("background-color","White");
var ID = $("#HiddenField2").attr("Value");
var params = { Key: ID };
$.post("viewMessages.aspx/readen", params);
});
});
var ID = $("#HiddenField2").val();
$.ajax({
type: "POST",
url: "viewMessages.aspx/readen",
data: {"KEY":ID},
contentType: "application/json",
dataType: "json"
});
Also you don't need to stringify the data component nor do you need to declare an new Object.