I try to send two arrays to the controller, each array from a different class. But all I get is alert with an error message. What am I doing wrong? When I send only one array in ajax data, it is obtained fine in the first array of the controller.
my code js:
$("#Button2").click(function () {
var dict = new Array();
$(":checkbox").each(function () {
if ($(this).prop("checked")== true) {
var key = this.name
if ($("input[name = 'r" + key + "']").length) {
dict.push({
Code: key,
Reccomendation: $("input[name = 'r" + key + "']").prop("value"),
});
}
else{
dict.push({
Code: key,
Reccomendation: $(this).prop("value"),
});
}
}
}) //end function each
var dict2 = new Array();
dict2.push({
Mentioned: $("#yesno").val(),
FollowUp: $("#Follo").val(),
UpdateCode:5
})
$.ajax({
type: 'POST',
url: "#Url.Action("SavevisitSummary")",
traditional: true,
dataType: 'JSON',
contentType: 'application/json; charset=utf-8',
data: { 'a': JSON.stringify(dict), 'b': JSON.stringify(dict2) },
success: function () {
alert("sucssec")
},
error:function(){
alert("error")
}
})
})
controller looks like:
public ActionResult SavevisitSummary(Reccomendations[] a, Summary[] b) { }
Related
I'm trying to post a single object data to an MVC Controler using JQuery, Below are my codes.
//declare of type Object of GroupData
var GroupData = {};
//pass each data into the object
GroupData.groupName = $('#groupName').val();
GroupData.narration = $('#narration').val();
GroupData.investmentCode = $('#investmentCode').val();
GroupData.isNew = isNewItem;
//send to server
$.ajax({
url: "/Admin/SaveContributionInvestGroup",
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify({ GroupData: JSON.stringify(GroupData) }),
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
Below is my controller.
[HttpPost]
public JsonResult SaveContributionInvestGroup(ContributionInvestmentGroup GroupData)
{
ClsResponse response = new ClsResponse();
ClsContributionInvestmentGroup clsClsContributionInvestmentGroup = new ClsContributionInvestmentGroup();
var userID = (int)Session["userID"];
var sessionID = (Session["sessionID"]).ToString();
if (contributionGroupData != null)
{
//get the data from the cient that was passed
ContributionInvestmentGroup objData = new ContributionInvestmentGroup()
{
contributionInvestmentGroupID = 0,
groupName = GroupData.groupName,
narration = GroupData.narration,
investmentCode = GroupData.investmentCode,
isNew = GroupData.isNew
};
response = clsClsContributionInvestmentGroup.initiateNewContributionInvestmentGroup(sessionID, objData);
}
else
{
response.IsException = true;
response.IsSucess = false;
response.Message = "A system exception occurred kindly contact your Administrator.";
}
return Json(new
{
response.IsSucess,
response.Message
});
}
The issue is, the data is not been posted to the controller, the controller receives a null object.
Kindly assist, would really appreciate your effort, thanks.
Try Like this:
//send to server
$.ajax({
type: "POST",
url: "/Admin/SaveContributionInvestGroup",
dataType: "json",
data: GroupData,
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
in your controller your dont have custom binding to bind JSON to your model thats why you get null in you parameter.
instead just post it as query, try simply changes your ajax option like so:
{
...
contentType: "application/x-www-form-urlencoded", //default:
...,
data: $.param(GroupData),
...
}
and perhaps property names are case sensitive so you will need to change your javascript model's name
i have a modal with input, i digit some emails and add to a list, later i want to pass this list of emails to my function that send emails.
var listEmails = [];
document.getElementById("addEmail").onclick = function () {
var text = document.getElementById("recipient-email").value;
$("#Listmail").append('<li>' + text + '</li>');
listEmails.push(text);
}
document.getElementById("sendEmail").onclick = function () {
#*location.href = '#Url.Action("TestSendReport", "ProductMarketplace")?emails='+listEmails;
}
that is my function in Controller that receive a list of email to send
public void TestSendReport(List<string> ListMails)
Please try below code and try to call controller method using jQuery Ajax
var list= [];
document.getElementById("addEmail").onclick = function () {
var text = document.getElementById("recipient-email").value;
$("#Listmail").append('<li>' + text + '</li>');
list.push(text);
}
document.getElementById("sendEmail").onclick = function () {
var jsonText = JSON.stringify({ list: list});
$.ajax({
type: "POST",
url: "ProductMarketplace/TestSendReport",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() { alert("success"); },
failure: function() { alert("failed"); }
});
}
And use controller method like this,
[WebMethod]
public void TestSendReport(List<string> list)
{
}
document.getElementById("sendEmail").onclick = function () {
location.href = '#Url.Action("TestSendReport", "ProductMarketplace")?emails=' +
encodeURI(JSON.stringify(listEmails));
}
public void TestSendReport(List<string> emails)
{
}
Here is the web method, which I use before for another thing, and it works:
[WebMethod]
public static string GetTests()
{
return GetData().GetXml();
}
public static DataSet GetData()
{
DataSet ds = new DataSet();
BusinessLayer.StudentsController oStudent = new BusinessLayer.StudentsController();
oStudent.Action = "page";
oStudent.PageIndex = 0;
oStudent.PageSize = int.Parse(System.Configuration.ConfigurationManager.AppSettings["PageSize"].ToString());
DataTable dt1 = oStudent.Select();
DataTable dt2 = dt1.Copy();
dt2.TableName = "Students";
ds.Tables.Add(dt2);
DataTable dt = new DataTable("PageCount");
dt.Columns.Add("PageCount");
dt.Rows.Add();
dt.Rows[0][0] = oStudent.PageCount;
ds.Tables.Add(dt);
return ds;
}
JavaScript:
$('#selectDynamic1').select2({
placeholder: "Search for a movie",
minimumInputLength: 1,
multiple: true,
ajax: {
url: "Default.aspx/GetTests",
type: 'POST',
params: {
contentType: 'application/json; charset=utf-8'
},
dataType: 'json',
data: function (term, page) {
return JSON.stringify({ q: term, page_limit: 10 });
},
results: function (data) {
return {results: data};
},
},
formatResult: formatResult,
formatSelection: formatSelection,
/*initSelection: function(element, callback) {
var data = [];
$(element.val().split(",")).each(function(i) {
var item = this.split(':');
data.push({
id: item[0],
title: item[1]
});
});
//$(element).val('');
callback(data);
}*/
});
function formatResult(node) {
alert('');
return '<div>' + node.id + '</div>';
};
function formatSelection(node) {
alert('');
return node.id;
};
Please help, GetTests is not even firing, I want to bring the student through SQL then fill the select2.
First, you shoul ry to change the HTTP verb to GET, as you are not posting data to the server, you want to get data from it:
ajax: {
...
type: 'GET',
...
}
Secondly, you are expecting JSON from the server, but in the GetData method, you are creating an XML document - at least the code conveys this. This may be one cause, why your code does not work.
I've got an array of Objects in jQuery:
function customersList() {
this.selectedCustomers = [];
}
function customerObject(customerId, bookingId) {
this.customerId = customerId;
this.bookingId = bookingId;
}
I need to post this to my Controller:
[HttpPost]
public ActionResult CreateMultipleCasesFormPost(CreateMultipleCasesModel model)
{
return PartialView("_CreateMultipleCases", model);
}
My ViewModel:
public class CreateMultipleCasesModel
{
[Display(Name = "Selected Customers")]
public List<CustomerList> Customers { get; set; }
I need to pass the Array from jQuery and the Data from this Form to my Controller (My View Model contains other properties):
$('#createMultipleCasesForm')
This is my Post Form jQuery Code:
$('#createMultipleCasesBtn').click(function () {
var btn = $(this);
var mUrl = btn.data('actionurl');
var formModel = $('#createMultipleCasesForm').serializeArray();
var customerList = customersList.selectedCustomers();
var requestData = {
model: formModel,
Customers: customerList
};
var sData = JSON.stringify(requestData);
$.ajax({
url: mUrl,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: sData,
success: function (response) {
debugger;
},
error: function (response) {
$('#ErrorMessage').html('<span class="icon black cross"></span>' + response.Message);
}
});
});
My Model from jQuery is not Binding either the Array of Customer Objects or the Form, What am I doing wrong here?
EDIT
What happens when I post Back my Form:
I found a solution this did the trick for me:
$('#createMultipleCasesBtn').click(function () {
var btn = $(this);
var mUrl = btn.data('actionurl');
var formModel = $('#createMultipleCasesForm').serializeObject();
formModel['Customers'] = customersList.selectedCustomers;
var sData = JSON.stringify(formModel);
$.ajax({
url: mUrl,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: sData,
success: function (response) {
},
error: function (response) {
$('#ErrorMessage').html('<span class="icon black cross"></span>' + response.Message);
}
});
});
This Function Below Used from Answer Here: Convert form data to JavaScript object with jQuery
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
I'm trying to collect a Facebook user info and then sign them up. How do i include more than one value in ajax?
$.signuser = function () {
FB.api('/me', function (response) {
var str = "";
alert(response.name);
var fbfname = response.first_name;
var fblname = response.last_name;
var fblname = response.id;
var fblink = response.link;
var fbusername = response.username;
var fblink = response.email;
$.ajax({
type: "POST",
data: {
data: fbfname,
fblname
},
complete: function () {
//$('#booksloadjif').css('display','none')
},
url: "fbpost.php"
}).done(function (feedback) {
$('#fg').html(feedback)
});
});
}
You can pass multiple key / value pairs to PHP as an object in $.ajax
$.signuser = function () {
FB.api('/me', function (response) {
var data = { // create object
fbfname : response.first_name,
fblname : response.last_name,
fblname : response.id,
fblink : response.link,
fbusername : response.username,
fblink : response.email
}
$.ajax({
type: "POST",
data: data, // pass as data
url: "fbpost.php"
}).done(function (feedback) {
$('#fg').html(feedback)
}).always(function() {
$('#booksloadjif').css('display','none')
});
});
}
and you'd access them in PHP with
$_POST['fbfname']
$_POST['fblname']
etc, i.e. the keynames in javascript are also the key names for the $_POST array