I have been trying to post two parameteres...
This is the ajax code
function Kaydet() {
var params = {};
var Kiralayan = $("#RentForm").serialize();
params.kisi = Kiralayan ;
params.aracid = P.AracID;
console.log(params);
$.ajax({
type: "POST",
url: '#Url.Action("Save","AracKirala")',
data: params,
dataType: "text",
success: function (response) {
if (response != "OK") {
alert("Kayıt yapılamadı.");
}
else {
document.getElementById("RentForm").reset();
alert("Kayıt başarıyla gerçekleştirildi.");
$("#myModal").modal('hide');
Ara();
}
}
});
Method
public ActionResult Save(Kiralayan kisi = null, int aracid = 0)
{
the problem is ajax posts "aracid" corretly but "kisi" turns null when the method is trigged...
I tried not to post "aracid" with "kisi" so ajax posted well for one parameter "kisi", but doesnt work together...
If you serializing the form, then you can add additional values to it with the .param() function
var data = $("#RentForm").serialize() + '&' + $.param({ 'aracid': AracID }, true);
$.ajax({
type: "POST",
url: '#Url.Action("Save","AracKirala")',
data: data,
....
MVC will map the object for you, so you might as well skip the extract nesting of the form within the object.
Notes:
If aracid is also a property in the model, it will map to both the property and the extra parameter.
Using push on the serialise() collection is more maintainable than the alternative of concatenating strings before the serialize() call.
e.g.
var Kiralayan = $("#RentForm").serialize();
// Add the extra non-form parameter
Kiralayan.push({name: 'aracid', value: P.AracID});
Full example:
function Kaydet() {
var Kiralayan = $("#RentForm").serialize();
// Add the extra non-form parameter
Kiralayan.push({name: 'aracid', value: P.AracID});
console.log(params);
$.ajax({
type: "POST",
url: '#Url.Action("Save","AracKirala")',
data: Kiralayan,
dataType: "text",
success: function (response) {
if (response != "OK") {
alert("Kayıt yapılamadı.");
}
else {
document.getElementById("RentForm").reset();
alert("Kayıt başarıyla gerçekleştirildi.");
$("#myModal").modal('hide');
Ara();
}
}
});
Related
I'm using ajax to send an int64 and a string from a month selector to my server-side, but my variable is always null or 0.
JS:
function deleteConta(id) {
var data = $("#monthSelector").val();
var params = {
id: id,
dataAtual: data
};
$.ajax({
type: "POST",
url: '/Contas/ContaView?handler=Delete',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(params),
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (partialReturn) {
$("#partial").html(partialReturn);
}
});
}
C#:
public PartialViewResult OnPostDelete([FromBody] long id, string dataAtual)
{
contaDTO.Remove(id, contaDTO.Database, contaDTO.ContaCollection);
dataCorrente = DateTime.ParseExact(dataAtual, "yyyy-MM", null).AddMonths(1);
contas = BuscarContasUsuarioMes(User.Identity.Name, dataCorrente);
return Partial("_PartialContas", contas);
}
I already checked with debugger and my variables are ok and filled with value expected (One test was like {id: 50, dataAtual: '2023-01'}
Checked a lot of forums, but Couldn't figure out how to make this thing work.
By declaring the number parameter with [FromBody] you tell ASP.NET Core to use the input formatter to bind the provided JSON (or XML) to a model. So your test should work, if you provide a simple model class.
Have you tried to remove it and sending value to the action?
—- UPDATE ——
Try this
function deleteConta(id) {
var data = $("#monthSelector").val();
$.ajax({
type: "POST",
url: '/Contas/ContaView?handler=Delete',
data: { id: id, dataAtual: data },
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (partialReturn) {
$("#partial").html(partialReturn);
}
});
}
I am calling jquery function on dropdown value change jquery method is ,
function MyFunction() {
alert($('#DDlSurvey').val());
$.ajax({
url: "#Url.Action("GetSelectedQuestion", "ConductSurveyController")",
data: { prefix: $('#DDlSurvey').val() },
type: "GET",
dataType: "json",
success: function (data) {
// loadData(data);
alert(data)
alert("Success");
},
error: function () {
alert("Failed! Please try again.");
}
});
//$('#YourLabelId').val('ReplaceWithThisValue');
}
</script>
Function I'm calling and I am getting dropdown value alert
Now, Function that I am calling is "GetSelectedQuestion" in controller "ConductSurveyController"
Method is like ,
[HttpPost]
public JsonResult GetSelectedQuestion(int prefix)
{
List<SelectList> Questions=new List<SelectList>();
// Here "MyDatabaseEntities " is dbContext, which is created at time of model creation.
SurveyAppEntities ObjectSur = new SurveyAppEntities();
// Questions = ObjectSur.Surveys.Where(a => a.ID.Equals(prefix)).toToList();
I don't think this method is calling as I am getting error
"Failed! Please try again"
From my script.
Hopes for your suggestions
Thanks
var e = from q in ObjectSur.Questions
join b in ObjectSur.SurveyQuestions on q.ID equals b.QuestionID where b.SurveyID.Equals(prefix)
select q ;
return new JsonResult { Data = e, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
I think you are using controller name straight forward. your ajax code be something like this.
var PostData= { prefix: $('#DDlSurvey').val() }
var ajaxOptions = {
type: "GET",
url: '#Url.Action("GetSelectedQuestion", "ConductSurvey")',//Actionname, ControllerName
data: PostData,
dataType: "json",
success: function (result) {
console.log(result);
},
error: function (result) {
}
};
$.ajax(ajaxOptions);
Your method in your controller is decorated with HttpPost, while in your ajax you have specified the type of your request is get . You can either change your method to get like this:
[HttpGet]
public JsonResult GetSelectedQuestion(int prefix)
{
}
Or change your request type to post in your Ajax call:
$.ajax({
url: "#Url.Action("GetSelectedQuestion", "ConductSurveyController")",
data: { prefix: $('#DDlSurvey').val() },
type: "Post",
Also the Controller is redundant in ConductSurveyController, you need to remove it and simply call it as ConductSurvey:
url: '#Url.Action("GetSelectedQuestion", "ConductSurvey")',
I have a view with multiple inputs for my Model (Html.TextBoxFor(x => x.attribute) etc. And my ajax method is:
function callMethod() {
$.ajax({
type: "POST",
data: $('#Form').serialize() ,
url: '#Url.Action("formMethod", "Test")',
}).done(function (newTable) {
$('#RefundTableDiv').html(newTable);
});
};
and this works perfectly, the model comes perfectly to formMethod, but when i change formMethod and add another parameter for example 'int test' it doesnt work anymore.
My method looks like:
function callMethod() {
var number = 2;
$.ajax({
type: "POST",
data: {"model": $('#Form').serialize(),
"test": number},
url: '#Url.Action("formMethod", "Test")',
}).done(function (newTable) {
$('#RefundTableDiv').html(newTable);
});
};
the "test": number does come correctly to the method in the controller but the model suddenly is null now?
What am i doing wrong?
Using .serialize() serializes your model as a query string (e.g. someProperty=someValue&anotherProperty=anotherValue&...). To add additional name/value pairs, you can append then manually, for example
var data = $('#Form').serialize() + '&test=' + number;
$.ajax({
....
data: data;
or use the param() method (useful if you have multiple items and/or arrays to add)
var data = $("#Form").serialize() + '&' + $.param({ test: number }, true);
$.ajax({
....
data: data;
you can do it like this:
function callMethod() {
var number = 2;
var sd = $('#Form').serializeArray();
sd.push({ name:"test", value:number });
$.ajax({
type: "POST",
data: sd,
url: '#Url.Action("formMethod", "Test")',
}).done(function (newTable) {
$('#RefundTableDiv').html(newTable);
});
};
I have been trying to post two parameteres...
This is the ajax code
function Kaydet() {
var params = {};
var Kiralayan = $("#RentForm").serialize();
params.kisi = Kiralayan ;
params.aracid = P.AracID;
console.log(params);
$.ajax({
type: "POST",
url: '#Url.Action("Save","AracKirala")',
data: params,
dataType: "text",
success: function (response) {
if (response != "OK") {
alert("Kayıt yapılamadı.");
}
else {
document.getElementById("RentForm").reset();
alert("Kayıt başarıyla gerçekleştirildi.");
$("#myModal").modal('hide');
Ara();
}
}
});
Method
public ActionResult Save(Kiralayan kisi = null, int aracid = 0)
{
the problem is ajax posts "aracid" corretly but "kisi" turns null when the method is trigged...
I tried not to post "aracid" with "kisi" so ajax posted well for one parameter "kisi", but doesnt work together...
If you serializing the form, then you can add additional values to it with the .param() function
var data = $("#RentForm").serialize() + '&' + $.param({ 'aracid': AracID }, true);
$.ajax({
type: "POST",
url: '#Url.Action("Save","AracKirala")',
data: data,
....
MVC will map the object for you, so you might as well skip the extract nesting of the form within the object.
Notes:
If aracid is also a property in the model, it will map to both the property and the extra parameter.
Using push on the serialise() collection is more maintainable than the alternative of concatenating strings before the serialize() call.
e.g.
var Kiralayan = $("#RentForm").serialize();
// Add the extra non-form parameter
Kiralayan.push({name: 'aracid', value: P.AracID});
Full example:
function Kaydet() {
var Kiralayan = $("#RentForm").serialize();
// Add the extra non-form parameter
Kiralayan.push({name: 'aracid', value: P.AracID});
console.log(params);
$.ajax({
type: "POST",
url: '#Url.Action("Save","AracKirala")',
data: Kiralayan,
dataType: "text",
success: function (response) {
if (response != "OK") {
alert("Kayıt yapılamadı.");
}
else {
document.getElementById("RentForm").reset();
alert("Kayıt başarıyla gerçekleştirildi.");
$("#myModal").modal('hide');
Ara();
}
}
});
I have a WebMethod, which is populating a JQuery DataTable with some initial values. I have a drop down list, which calls the WebMethod and try to populate it with different values. My problem, is if the JSON data is null (or '') then i get JSON.parse: unexpected end of data.
Now, I can check the length of the object using if(msg.d.length !- '' { build the table} ) However, if the length is null (''), then i never go into the build table, and therefore cant present that there is no data / no records.
How can I ensure that if the JSON string/object is null ('') that DataTables still presents No Records found etc...?
$('#ddBICS').change(function (e) {
var val = $('#dd option:selected').text();
msgDateDetail(val);
});
function msgDateDetail(value) {
$.ajax({
type: "POST",
url: "Default.aspx/MsgDateDetail",
cache: false,
data: JSON.stringify({ searchValue: value }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var data = JSON.parse(msg.d);
var asInitVals = new Array();
otblMsgDateDetail = $("#tblMsgDateDetail").dataTable({
"sDom": "<'row-fluid'<'span6'T><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"oTableTools": {
"aButtons": [
"copy",
"print",
{
"sExtends": "collection",
"sButtonText": 'Save <span class="caret" />',
"aButtons": ["csv", "xls", "pdf"]
}
]
},
"aaData": data
})
}
});
}
msg could be null or undefined, just checking for the variable will tell you that. Also since you're using JQuery you could check if d is an array with the isArray JQuery method.
if(msg && msg.d && $.isArray(msg.d) && msg.d.length > 0) {
// build the table
}else{
// data is empty
}
Within your above method you would do the following.
function msgDateDetail(value) {
$('#tblMsgDate
$.ajax({
type: "POST",
url: "Default.aspx/MsgDateDetail",
cache: false,
data: JSON.stringify({ searchValue: value }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var asInitVals = new Array();
var data = (msg && msg.d && $.isArray(msg.d))? msg.d : new Array();
otblMsgDateDetail = $("#tblMsgDateDetail").dataTable({
"sDom": "<'row-fluid'<'span6'T><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"oTableTools": {
"aButtons": [
"copy",
"print",
{
"sExtends": "collection",
"sButtonText": 'Save <span class="caret" />',
"aButtons": ["csv", "xls", "pdf"]
}
]
},
"aaData": data
})
}
});
}
The documentation for the jquery method is located on jquery.com http://api.jquery.com/jQuery.isArray/
For this to work make sure that your Default.aspx/MsgDateDetail returns application/json for the content type. To do this in the aspx file you do the following:
Response.ContentType = "application/json"
You must do this before you do any Response.Write
You should the length like this
if(msg.d.length !=0) { // Try this
//-- build the table
}