I am trying to send data via AJAX to MVC Controller method. I am trying to make booking system app. I want to check that user input exists in Entity Model. Ajax is pushing parameters to method controller but i don't get response.
Here is my AJAX call in View:
var check = document.getElementById('check');
//starttime.onchange = checkvalidate(startdate, starttime);
$(check).click(function (datevalue, timevalue) {
var startdate = document.getElementById('startdate');
var starttime = document.getElementById('starttime');
var log = document.getElementById('log');
var datevalue = startdate.value;
var timevalue = starttime.value;
$.ajax({
type: "POST",
url: "/Home/CheckValidate",
data: { 'start': datevalue, 'time': timevalue },
dataType: "Boolean",
success: function (response) {
console.log = response;
if (response == true) {
log.value = "YES";
} else
{
log.value = "NO";
}
}
})
})
And method in controller:
public bool CheckValidate(string start, string time)
{
string datastart = start + " " + time;
DateTime startDate = Convert.ToDateTime(datastart);
EventsEntities dc = new EventsEntities();
var MatchedElements = dc.Events.Where(x => x.start <= startDate && startDate < x.end).FirstOrDefault();
if (MatchedElements == null)
{
return true;
} else
{
return false;
}
}
I want to send string inputs and get back data to show message that is possible to book that room.
Where did I mistake?
You can do like this.
var obj = {};
obj.startdate = document.getElementById('startdate');
obj.starttime = document.getElementById('starttime');
$.ajax({
type: "POST",
url: "/Home/CheckValidate",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
//failure message
}
});
function OnSuccess(response) {
//do your stuff after success response
}
There are a few things missing from your ajax call. You need to specify data you're sending in such way so that it is sent as JSON and properly. To do that you need to stringify your javascript json object and declare that you're sending a JSON data type. Here is your click event handler code with changes:
$(check).click(function () {
var data = {
start: datevalue,
time: timevalue
};
$.ajax({
type: "POST",
url: "/Home/CheckValidate",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "boolean",
success: function (response) {
if (response) {
log.val = "YES";
} else {
log.val = "NO";
}
}
})
});
You can read more about it here: jquery ajax documentation
There are also other existing question here that already answer your question such as this one.
Related
I'm a newbie working with ajax. I have a problem while sending the data into ajax post.
The output of console.log(obj.Id) and console.log(oke) is 2. Then I tried to send it through data in ajax, but it end up 0 in the controller.
$(function () {
$("body").on('click', '#btnEdit', function () {
alert("clicked ok");
$("#addRowModal").modal("hide");
var obj = {};
obj.Id = $(this).attr('data-id');
oke = $(this).data("id");
console.log(obj.Id)
console.log(oke)
$.ajax({
url: '#Url.Action("Details", "InvoicePPh")',
data: oke,
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("sukses");
},
error: function(response) {
alert("error")
}
});
});
});
And my controller looks like this
[HttpPost]
public JsonResult Details(int id)
{
var obj = dbContext.invoicePPhs.FirstOrDefault(s => s.Id == id);
InvoicePPh pph = new InvoicePPh();
pph2326.TaxForm = obj.TaxForm;
return Json(pph);
}
I want the '2' value that passes into my controller, how can I do that? Thank you for your help.
An alternative way to send your data your Controller method using Ajax would be to wrap your data in a JSON object and then send it to the server for processing. The server will be then deserialize your JSON object and you can access the required properties from that process:
$(function () {
$("body").on('click', '#btnEdit', function () {
alert("clicked ok");
$("#addRowModal").modal("hide");
var obj = {};
obj.Id = $(this).attr('data-id');
oke = $(this).data("id");
console.log(obj.Id)
console.log(oke)
var json = {
oke: oke
};
$.ajax({
url: '#Url.Action("Details", "InvoicePPh")',
data: {'json': JSON.stringify(json)},
type: 'POST',
dataType: "json",
success: function (response) {
alert("sukses");
},
error: function(response) {
alert("error")
}
});
});
});
And your Controller method will be:
using System.Web.Script.Serialization;
[HttpPost]
public JsonResult Details(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
var id= Convert.Int32(jsondata["id"]);
var obj = dbContext.invoicePPhs.FirstOrDefault(s => s.Id == id);
InvoicePPh pph = new InvoicePPh();
pph2326.TaxForm = obj.TaxForm;
return Json(pph);
}
If you just need id in your method parameter just change data in ajax to:
contentType: "application/x-www-form-urlencoded",
data: { 'id': oke },
id is name of parameter from controller method.
Please change the data property in ajax part.
$.ajax({
url: '#Url.Action("Details", "InvoicePPh")',
data: { 'id': oke },
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("sukses");
},
error: function(response) {
alert("error")
}
});
I use Asp.Net WebApi and jQuery.
From page to WebApi i send 'POST' HTTP-Request with object.
$.ajax({
type: "POST",
url: "api/Result",
data: JSON.stringify(makeResultInfo()),//makeResultInfo - function that returns object
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data) {
window.location = data;
alert("success");
},
error: function (xhr) {
alert('error');
}
});
WebApi take object correctly and return Excel-file.
[HttpPost]
public HttpResponseMessage Post([FromBody]ResultInfo value)
{
ExcelClass ec = new ExcelClass();
var stream = ec.GetStream(ec.mini_wb);//после теста поправить
// processing the stream.
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.ToArray())
};
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "test.xlsx"
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
When i make Request to 'api/Result' without parameters - file downloading correctly. But when i send object, response incorrect always and alert always write 'error'.
How i can send object and take file in browser?
I am using Angular Js with JQuery in a noodles way. See my code below.
Code
app.controller('ClassController', function ($scope) {
$scope.ShowHideNoRecords = false;
var credentials = new Object();
credentials.SourceName = "###";
credentials.SourcePassword = "###";
credentials.UserName = "###";
credentials.UserPassword = "##";
credentials.SiteId = [-99];
var locationIds = [1];
var startDate = Date.today();
var endDate = startDate;
var dto = { credentials: credentials, startDate: startDate, endDate: endDate, locationId: locationIds };
$.ajax({
type: "POST",
url: 'MbApiConnector.asmx/GetAllClasses',
data: JSON.stringify(dto),
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (response) {
alert(response.d);
},
complete: function (msg) {
$scope.$apply(function () {
$scope.Classes = JSON.parse(JSON.parse(msg.responseText).d);
if ($scope.Classes.length > 0) {
$scope.checkin = function (id) {
dto = { credentials: credentials, classId: id };
$.ajax({
type: "POST",
url: 'MbApiConnector.asmx/Checkin',
data: JSON.stringify(dto),
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
complete: function (msg) {
alert(msg.responseText);
}
});
}
}
else {
$scope.ShowHideNoRecords = true;
}
});
}
});
});
Everything is working fine with this code. I knew its a bad idea mixing the two but my app was already developed in Jquery Ajax and we are upgrading with Angular JS but with lesser changes. So I came up with this solution.
Anyways, my issues is that jquery ajax success function is not get called. I am able to receive data from the webservice , but inside the complete method, as you can see in the code above.
Can you explain me why its behaving so?
May be Jquery fails to parse it as the result may not be in JSON format, try to find the error using error callback function. You could try with dataType : 'json'.
error: function (err) { alert(err) }
In a AJAX request to the server in MVC, how can I pass a list of id's to the controller's action function?
I accept with or without use of Html helpers.
I know MVC's model binder has no problem when it comes to simple types like int, string and bool.
Is it something like I have to use and array instead in the action?
I don't care if I have to use an array or List and even if the strings I int or strings I can always convert them. I just need them on the server.
My List ids gives null at the moment.
Javascript:
var ids= [1,4,5];
// ajax request with ids..
MVC Action:
public ActionResult ShowComputerPackageBuffer(List<int> ids) // ids are null
{
// build model ect..
return PartialView(model);
}
EDIT: Added my AJAX request
$(document).ready(function () {
$('#spanComputerPackagesBuffer').on('click', function () {
var ids = $('#divComputerPackagesBuffer').data('buffer');
console.log('bufferIds: ' + bufferIds);
var data = {
ids: ids
};
var url = getUrlShowComputerPackageBuffer();
loadTable(url, "result", data);
});
});
// AJAX's
function loadTable(url, updateTargetId, data) {
var promise = $.ajax({
url: url,
dataType: "html",
data: data
})
.done(function (result) {
$('#' + updateTargetId).html(result);
})
.fail(function (jqXhr, textStatus, errorThrown) {
var errMsg = textStatus.toUpperCase() + ": " + errorThrown + '. Could not load HTML.';
alert(errMsg);
});
};
// URL's
function getUrlShowComputerPackageBuffer() {
return '#Url.Action("ShowComputerPackageBuffer", "Buffer")';
};
SOLUTIONS: // Thanks to #aherrick comment. I missed the good old "traditional"
$.ajax({
type: "POST",
url: '#Url.Action("ShowComputerPackageBuffer", "Buffer")',
dataType: "json",
traditional: true,
data: {
bufferIds: bufferIds
}
});
Use the traditional parameter and set it to true.
$.ajax({
type: "POST",
url: "/URL",
dataType: "json",
traditional: true,
data: {}
});
Try this one (I've checked it):
$(function () {
var ids = [1, 4, 5];
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '#Url.Action("YourAction", "YourController")',
data: JSON.stringify( { ids: ids })
}).done(function () {
});
});
You have to make sure your contentType is application/json and your data is stringified.
public ActionResult SaveSomething(int[] requestData)
//or
public ActionResult SaveSomething(IEnumerable<int> requestData)
Using Action Result you cannot receive JSON object:
Using Controler:
[HttpPost]
[Route( "api/Controller/SaveSomething" )]
public object SaveTimeSheet( int[] requestData )
{
try
{
doSomethingWith( requestData );
return new
{
status = "Ok",
message = "Updated!"
};
}
catch( Exception ex )
{
return new
{
status = "Error",
message = ex.Message
};
}
}
java script:
var ids = [1,4,5];
var baseUrl: 'localhost/yourwebsite'
$.ajax({
url: baseUrl + '/api/Controller/SaveSomething',
type: 'POST',
data: JSON.stringify(ids),
dataType: 'json',
contentType: 'application/json',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
if (result != undefined) {
window.location.href = window.location.href;
}
},
async: false,
});
I have a variable called sid which handle number of seat. I want to throw sid to TryJSON.aspx method test. then I wanna do manipulate data on method test then throw back the result to this ajax. but I have an error when I just try to throw sid
var sid = jQuery(this).attr('id');
console.log(sid);
$.ajax({
url: "TryJSON.aspx/test",
type: "POST",
data: JSON.stringify({ 'noSeat': sid }),
contentType: "application/json; charset=utf-8",
success: function (response) {
var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});
this is my C# code to receive noSeat
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
// return noSeat;
//JavaScriptSerializer serializer = new JavaScriptSerializer();
// return new JavaScriptSerializer().Serialize(new { noSeat = noSeat });
}
I have try return only noSeat and also with Javascript serializer. but it has an error. it says
An attempt was made to call the method 'test' using a POST request, which is not allowed.
I have been tried
return "Success !!"
but it doesn't appear on console and still same error.
what's the matter ?
var sid = jQuery(this).attr('id');
console.log(sid);
$.ajax({
url: "TryJSON.aspx/test",
type: "POST",
data: JSON.stringify({ 'noSeat': sid }),
contentType: "application/json; charset=utf-8",
dataType:'json',
success: function (response) {
var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});