ajax jquery pass null value - asp.net-mvc-3

I get null values in the controller when I process the request using jquery ajax
Controller
[HttpPost]
public ActionResult UpdateAnswers(string answers, string question, string controlid, int eventid)
{
var replacetext=string.Empty;
if (answers.Length>0)
replacetext = answers.Replace("\n", ",");
_service.UpdateAnswers(eventid, replacetext, controlid);
return PartialView("CustomizedQuestions");
}
Jquery - Ajax Code
var test = "{ answers: '" + $("#answerlist").val() + "', question: '" + title + "', controlid: '" + controlid + "', eventid: '" + eventid + "' }";
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
contentType: 'application/html; charset=utf-8',
context: $(this),
// data: "{ answers: '"+$("#answerlist").val()+"' ,question: '"+ title +"', controlid:'"+ controlid +"',eventid:'"+ eventid+"'}",
data: JSON.stringify(test),
success: function (result) {
$(this).dialog("close");
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});

Your contentType is wrong. Why did you set it to application/html when you pass JSON? Try like this:
var test = { answers: $('#answerlist').val(), question: title, controlid: controlid, eventid: eventid };
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
contentType: 'application/json; charset=utf-8',
context: $(this),
data: JSON.stringify(test),
success: function (result) {
$(this).dialog("close");
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});
or using application/x-www-form-urlencoded which is the default:
var test = { answers: $('#answerlist').val(), question: title, controlid: controlid, eventid: eventid };
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
context: $(this),
data: test,
success: function (result) {
$(this).dialog('close');
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});

Related

How to send success or failure status to AJAX calls from Asp.Net Web API

I am working on an asp.net C# Web API project. I am posting data from a client using jQuery AJAX. The code is given below. I have tried two types of AJAX calls as shown below. Whether the API succeeds or not, the code under either success or error is never reached in the AJAX.
Asp.Net Web API Code:
[HttpPost]
[Route("SendCustomerDetails")]
public async Task<IHttpActionResult> SendCustomerDetails([FromBody] String jsonData)
{
//Code to process json
//...
//...
resp = await client.PostAsJsonAsync("customer/newcustomer", jObject);
if (resp.IsSuccessStatusCode)
{
//log resp
return Created(Request.RequestUri.ToString(), resp.StatusCode);
}
else{
//log resp
return Created(Request.RequestUri.ToString(), resp.StatusCode);
}
}
Jquery AJAX code1:
$.ajax({
type: 'POST',
url: 'http://localhost:49918/SendCustomerDetails',
dataType: 'json',
//data: jsonData,
data: JSON.stringify(jsonData),
contentType: "application/json"
}).done(function (data) {
alert("Success: " + data);
$('#value1').text(data);
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("failure: " + jqXHR.responseText || textStatus);
$('#value1').text(jqXHR.responseText || textStatus);
});
Jquery AJAX code2:
$.ajax({
type: 'POST',
url: 'http://localhost:49918/SendCustomerDetails',
dataType: 'json',
//data: jsonData,
data: JSON.stringify(jsonData),
contentType: "application/json",
success: function(data) {
alert("Success: " + data);
},
error: function (data) {
alert("error: " + JSON.stringify(data));
}
});
fix the action
[HttpPost]
[Route("~/SendCustomerDetails")]
public IActionResult SendCustomerDetails(JObject model)
{
return Ok(" It is Success");
}
try this code
$.ajax({
type: 'POST',
url: 'http://localhost:49918/SendCustomerDetails',
data: { model:jsonData},
success: function(data) {
alert("Success: " + JSON.stringify(data));
},
error: function (data) {
alert("error: " + JSON.stringify(data));
}
});

Returning error from controller to AJAX jQuery

I works with ASP.net MVC and I have get "Error" from belowe my JavaScript code:
This is my AJAX jQuery code:
$(document).ready(function () {
var dataId;
$(".item2 .small-img").click(function () {
dataId = $(this).data("id");
var url = '#Url.Action("DecorationTest", "Carpet")' + "?Id=" + dataId + "&title=" + '#Url.ToFriendlyUrl(Model.Title.ToString())';
$('#dateLink').prop('href', url);
$.ajax({
url: '/Carpet/CheckCarpet',
type: 'POST',
dataType: 'Json',
data: '{"CarpetImageid":"' + dataId + '"}',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.Success == false)
$('#dateLink').hide();
else
$('#dateLink').show();
alert("Success");
},
error: function (errorThrown) {
alert("Error");
}
});
and this is a controller code:
[HttpPost]
public ActionResult CheckCarpet(int CarpetImageid)
{
bool DecorShow = false;
DecorShow = db.Images.Where(x => x.Id == CarpetImageid).FirstOrDefault().DecorTest;
return Json(new JsonData { Success= DecorShow });
}
what's the reason? Someone knows?
I found the solution.i change url to #Url.Action("CheckCarpet", "Carpet") and fixed.
$(".small-img").click(function () {
dataId = $(this).data("id");
var url = '#Url.Action("DecorationTest", "Carpet")' + "?Id=" + dataId + "&title=" + '#Url.ToFriendlyUrl(Model.Title.ToString())';
$('#dateLink').attr('href', url);
$.ajax({
url:'#Url.Action("CheckCarpet", "Carpet")',
type: 'Post',
dataType: 'Json',
data: '{"CarpetImageid":"' + dataId + '"}',
contentType: 'application/json; charset=utf-8',
success: function (result) {
if (result.Success == false) {
$('#dateLink').hide();
$('.p2').hide();
}
else {
$('#dateLink').show();
$('.p2').show();
}
},
error: function (error) {
alert(error.d);
}
});
});

unsupported_grant_type in Web Api 2

i am beginner in Web Api and implementing authorization and authentication but getting some error as i mentioned below:
I am getting this error while getting token from webApi
{"readyState":4,"responseText":"{\"error\":\"unsupported_grant_type\"}","responseJSON":{"error":"unsupported_grant_type"},"status":400,"statusText":"Bad Request"}
This is my jQuery code to make request for token
$(document).ready(function () {
$("#login").click(function () {
debugger;
var details = "{'grant_type':'password', 'username': '" + $("#UserName").val() + "', 'password': '" + $("#Password").val() + "' }";
console.log(details);
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded",
data: details,
url: "http://localhost:59926/token",
success: function (data) { console.log(JSON.stringify(data)); },
error: function (data) { console.log(JSON.stringify(data)); }
});
});
Your data should be like query string, not JSON object. And you should encode params if need
data: 'username=' + encodeURIComponent(user.username) + '&password=' + encodeURIComponent(user.password) + '&grant_type=password'
contentType is wrong. It should be application/json
$(document).ready(function () {
$("#login").click(function () {
debugger;
var details = "{'grant_type':'password', 'username': '" + $("#UserName").val() + "', 'password': '" + $("#Password").val() + "' }";
console.log(details);
$.ajax({
type: "POST",
contentType: "application/json",
data: details,
url: "http://localhost:59926/token",
success: function (data) { console.log(JSON.stringify(data)); },
error: function (data) { console.log(JSON.stringify(data)); }
});
});

display values returned by json

I have simple question to display data on html page. Following code displays array of json data on screen. but, I want to display it by each element such as "url", "img_url" and so on.
could you please let me know who to do it ?
ajax code
var dataString = 'url=' + pathname + '&img_name=' + img_name + "&tag=" + tag;
$.ajax({
type: "POST",
url: "image_finder.php",
data: dataString,
dataType: 'json',
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
//handleError();
alert("error");
} else {
var data = xhr.responseText;
$('#tt').html("<div id='message'></div>");
$('#message').html(data);
}
}
});
json return
{"cid":"14","url":"http:\/\/localhost\/","img_url":"http:\/\/static.naver.net\/www\/up\/2013\/0305\/mat_173330634c.jpg","img_name":"mat_173317134c.jpg","html":"<div id=\"hotspot-19\" class=\"hs-wrap hs-loading\">\r\n<img src=\"http:\/\/static.naver.net\/www\/up\/2013\/0305\/mat_173330634c.jpg\">\r\n<div class=\"hs-spot-object\" data-type=\"spot\" data-x=\"95\" data-y=\"64\" data-width=\"30\" data-height=\"30\" data-popup-position=\"left\" data-visible=\"visible\" data-tooltip-width=\"200\" data-tooltip-auto-width=\"true\">\r\nasdf\r\n<\/div>\r\n<div class=\"hs-spot-object\" data-type=\"spot\" data-x=\"168\" data-y=\"53\" data-width=\"30\" data-height=\"30\" data-popup-position=\"left\" data-visible=\"visible\" data-tooltip-width=\"200\" data-tooltip-auto-width=\"true\">\r\nrere\r\n<\/div>\r\n<\/div>\r\n","jscript":""}
$.ajax({
type: "POST",
url: "image_finder.php",
data: dataString,
dataType: 'json',
success: function (data) {
for(var item in data){
console.info(item);//print key
console.info(data[item]);//print value
}
}
});
I hope this is what you need.

Ajax Json multiple parameters

This code below sitting on a ASP.Net application on the Site.Mater....
I need to pass another two parameters from the default.aspx page, one asp:label and one asp:textbox
What is the easiest way to do that?
Thanks
<script type="text/javascript">
$(function () {
$(".tb").autocomplete({
source: function (request, response) {
$.ajax({
url: "TestWebService.asmx/FetchList",
data: "{ 'testName': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.Name
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
In your jQuery autocomplete, You need to change your data parameter to this:
data: "{ 'testName': '" + request.term + "' ,lbl: '" + $(".lblClass").text() + "' ,txt: '" + $(".txtClass").val() + "'}"
And then change your service method like this:
[WebMethod]
public List<string> FetchList(string testName, string lbl, string txt)
{
//...
}
Note:
.lblClass and .txtClass are classes for ASP:Lable and ASP:TextBox respectively.

Resources