Posting Array and Form Data to Controller - MVC Ajax - javascript

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;
};

Related

Need to send list of objects and other object to controller using ajax post

Need to send list of object and other object to controller using ajax post method. When i try to send using ajax post method using view model then list always null. Below is the code.
JavaScript Code:
function SubmitForm() {
var ServiceDefinition = $("#frmService").serialize();
var clinicServiceList = [];
$(".chkUserLocation:checked").each(function () {
var checkBoxId = $(this).prop("id");
checkBoxId = "#accordion" + checkBoxId;
var emergencyPrice = $(checkBoxId).find(".clsEmergencyPrice").val();
var opdPrice = $(checkBoxId).find(".clsOpdPrice").val();
var ipdPrice = $(checkBoxId).find(".clsIPDPrice").val();
var statPrice = $(checkBoxId).find(".clsStatPrice").val();
var clinicServiceId = $(checkBoxId).find(".hdnClinicServiceId").val();
clinicServiceList.push({
'OpdPrice': opdPrice,
'IpdPrice': ipdPrice,
'ERPrice': emergencyPrice,
'StatPrice': statPrice,
'LocationId': $(this).prop("id"),
'ClinicServiceId': clinicServiceId
});
});
var data1 = { 'clinicServices': clinicServiceList };
var data = JSON.stringify(data1);
var serviceDefination = { 'ServiceDefinition': ServiceDefinition };
var serviceViewModel = {
'ServiceDefinition': ServiceDefinition,
'clinicServices': JSON.stringify(clinicServiceList)
}
$.ajax({
url: '#Url.Action("ServiceForm", "Service")',
type: "POST",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: serviceViewModel,
async: true,
success: function (msg) {
},
error: function (result) {
}
});
}
Controller Code:
public ActionResult ServiceForm(ClinicServiceViewModel serviceViewModel)
{
return json(result);
}
Model Code:
public class ClinicServiceViewModel
{
public ClinicServiceViewModel()
{
ServiceDefinition = new ServiceDefinition();
ClinicServices = new List<ClinicService>();
}
public ServiceDefinition ServiceDefinition { get; set; }
public List<ClinicService> ClinicServices { get; set; }
}
Any one guide where i am making mistake?
please try:
var serviceViewModel = {
'ServiceDefinition': ServiceDefinition,
'clinicServices': clinicServiceList
}
data: JSON.stringify(serviceViewModel),

how to send two arrays to controller via ajax

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) { }

Pass list javascript in parameter ASP.NET

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)
{
}

JQuery TypeError: Converting circular structure to JSON in MVC

Facing error on JSON.stringify(ApplObj) :
How to post this object to controller
JQuery Code -
var ApplName = $("#ApplicantName").val();
var ApplMobile = $("#ApplicantMobile").val();
var ApplEmail = $("#ApplicantEmailId").val();
var ApplFHName = $("#ApplicantFHName").val();
var ApplObj = {
ApplicantName: ApplName, ApplicantMobile: ApplMobile, ApplicantEmailId: ApplEmail, ApplFHName: ApplicantFHName
}
$.ajax({
url: '#Url.Action("SaveApplicatDetail", "Dashboard")',
data: JSON.stringify(ApplObj),
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
}
});
Controller Code...
this jsonresult used for save records and return value...
this code is working in other project....
public JsonResult SaveApplicatDetail()
{
try
{
var resolveRequest = HttpContext.Request;
TicketMasterModel TMM = new TicketMasterModel();
resolveRequest.InputStream.Seek(0, SeekOrigin.Begin);
string jsonString = new StreamReader(resolveRequest.InputStream).ReadToEnd();
if (jsonString != null)
{
TMM = (TicketMasterModel)js.Deserialize(jsonString, typeof(TicketMasterModel));
}
int TicketId = 0;
using (var db = new UnitOfWork())
{
DAL.tbl_TrnTicketMaster TM = new DAL.tbl_TrnTicketMaster();
TM.ApplicantName = TMM.ApplicantName;
TM.ApplicantMobile = TMM.ApplicantMobile;
TM.ApplicantEmailId = TMM.ApplicantEmailId;
TM.ApplicantFHName = TMM.ApplicantFHName;
TM.FK_CompanyId = 1;
TM.CustomerId = UserSession.UserId;
TM.IsSubmissionLocked = false;
TM.CreatedBy = UserSession.UserId;
db.tbl_TrnTicketMaster.Insert(TM);
TicketId = TM.PK_TicketId;
}
return Json(TicketId, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
throw;
}
}
basically JSON.stringify turns a Javascript object into JSON text and stores that JSON text in a string.
try this,
var ApplName = $("#ApplicantName").val();
var ApplMobile = $("#ApplicantMobile").val();
var ApplEmail = $("#ApplicantEmailId").val();
var ApplFHName = $("#ApplicantFHName").val();
var ApplObj = {
'ApplicantName': ApplName, 'ApplicantMobile': ApplMobile, 'ApplicantEmailId': ApplEmail, 'ApplFHName': ApplicantFHName
}
$.ajax({
url: '#Url.Action("SaveApplicatDetail", "Dashboard")',
data: JSON.stringify(ApplObj),
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
}
});
Problem Resolved -
"JSON.stringify" is used array to convert it.
var ApplName = $("#ApplicantName").val();
var ApplMobile = $("#ApplicantMobile").val();
var ApplEmail = $("#ApplicantEmailId").val();
var ApplFHName = $("#ApplicantFHName").val();
var ApplDetails = {
ApplicantName: ApplName,
ApplicantMobile: ApplMobile,
ApplicantEmailId: ApplEmail,
ApplicantFHName: ApplFHName
}
var ApplObj = { ApplicantDetail: ApplDetails };
$.ajax({
url: '#Url.Action("SaveApplicatDetail", "Dashboard")',
data: JSON.stringify(ApplDetails),
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
}
});

How to send multiple values using ajax to PHP

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

Categories