Pass list javascript in parameter ASP.NET - javascript

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

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),

Saving changes to the DB MVC

I have a problem when I try to save some data to the database. I can see the ID and Date returning me appropriate values in the JS function... However, the parameter for the Process function inside the controller class remains null. I don't know why is that happening. There is a linq query that is also included in the Hello Model, but I didn't include it because there is no need for it.
Model:
public class Hello
{
List<string> Ids { get; set; }
List<string> Dates { get; set; }
}
Controller:
[HttpPost]
public ActionResult Process(string ids, string dates)
{
Hello model = new Hello();
if (ModelState.IsValid)
{
using (db = new DB())
{
rp = new RequestProcess();
//var c = rp.getHello(model, dates);
var c = rp.getStuff();
if (c != null)
{
foreach (var i in c)
{
if (i != null)
{
ids = i.ID;
dates = i.Date.ToString();
}
db.SaveChanges();
}
}
}
ViewBag.Message = "Success";
return View(model);
}
else
{
ViewBag.Message = "Failed";
return View(model);
}
}
View:
<td><input class="id" type="checkbox" id=#item.ID /></td>
<td>#Html.DisplayFor(x => #item.ID)</td>
<td><input class="date" id=date#item.ID type="text" value='#item.Date'/></td>
$(document).ready(function () {
var ids = "";
var dates = "";
$("#btnSubmit").bind("click", function () {
createUpdateArrays();
var url = "/Sample/Process";
$.ajax({
type: "POST",
url: url,
data: { ids: ids, dates: dates },
contentType: 'application/json; charset=utf-8',
success: function (success) {
if (success === true) {
alert("HERE WE ARE");
}
else {
alert("eror");
}
}
});
ids = "";
dates = "";
});
function createUpdateArrays() {
var i = 0;
$('input.remedy-id:checkbox').each(function () {
if ($(this).is(':checked')) {
var rid = $(this).attr("id");
$('.planned-date').each(function () {
var did = $(this).attr("id");
if (did === rid) {
var date = $(this).val();
ids += rid + ",";
dates += date + ",";
}
});
};
});
};
Any help would be appreciated!
I think you need contentType: 'application/json' in your $.ajax({});
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(list),
contentType: 'application/json'
});
Also, try adding [FromBody]Hello model in your controller action.
There are several issues in your code:
1) You're passing JSON string containing viewmodel properties, it is necessary to set contentType: 'application/json; charset=utf-8' option in AJAX callback to ensure model binder recognize it as viewmodel parameter.
2) return View() is not applicable for AJAX response, use return PartialView() instead and put html() to render response in target element.
Therefore, you should use AJAX setup as provided below:
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(list),
contentType: 'application/json; charset=utf-8',
success: function (result) {
$('#targetElement').html(result);
},
error: function (xhr, status, err) {
// error handling
}
});
Controller Action
[HttpPost]
public ActionResult Process(Hello model)
{
if (ModelState.IsValid)
{
using (db = new DB())
{
// save data
}
ViewBag.Message = "Success";
return PartialView("_PartialViewName", model);
}
else
{
ViewBag.Message = "Failed";
return PartialView("_PartialViewName", model);
}
}
Remember that AJAX callback intended to update certain HTML element without reloading entire view page. If you want to reload the page with submitted results, use normal form submit instead (with Html.BeginForm()).

What to do if Optional Parameter concept doesn't work?

I have a JS function which takes a value from a textbox based on the Radio button selected.
Example: If RadioButton No is Selected, values is teken from TextBox A, else if RadioButton Yes is selected, Value is taken from TextBox B. The following script is in my view
$('#btnVolunteerSaveBtn').on('click', function() { // on click of save button
if (document.getElementById('RadioNo').checked) { //ID of radio button NO
var checking = $('#Donation').val(); //ID of textbox from where the value is to be taken if RadioButton No is selected
if (checking == "") {
//if nothing is entered, stop from saving in DB
} else {
x = $('#Donation').val(); //ID of textbox from where the value is to be taken if RadioButton No is selected
$.ajax({
url: '#Url.Action("DonationValue","VolunteerInfo")',
data: {
name: x
},
type: "POST"
});
}
} else {
x = $('#GetNames').val(); //ID of textbox from where the value is to be taken if RadioButton Yes is selected
$.ajax({
url: '#Url.Action("DonationValue","VolunteerInfo")',
data: {
name: x
},
type: "POST"
});
}
});
Till here it seems to work fine. Now coming to the controller, I have a function DonationValue
My Question:
How can I pass the name parameter above?
If nothing is filled in TextBox with id #Donation, how do I stop
from saving the form in the DB?
My Attempt:
I tried doing
public string DonationValue(string name = null)
{
return name; //Trying to pass this value above
}
This didn't help. It resolved the error but the passed value was always null. I also tried a couple of other things but none helped.
Edited:
[HttpPost]
public ActionResult AddVolunteer(VolunteerInfo viewModel)
{
if (!ModelState.IsValid)
{
return View("AddVolunteer", viewModel);
}
var volunteer = new VolunteerInfo()
{
Name = viewModel.Name,
BirthdayDateTime = viewModel.BirthdayDateTime,
Address = viewModel.Address,
PhoneNumber = viewModel.PhoneNumber,
EmailAddress = viewModel.EmailAddress,
OccasionsID = viewModel.OccasionsID,
DonationForWhom = _DonationValue
};
if (!string.IsNullOrEmpty(volunteer.DonationForWhom))
{
_context.VolunteerInfos.Add(volunteer);
_context.SaveChanges();
return RedirectToAction("Index", "Home");
}
return //something to save state so that user doesnt have to enter all the values again
}
[HttpPost]
public void DonationValue(string name)
{
_DonationValue = name;
}
#Daisy Shipton.
Is this a better solution?
<script>
$(function() {
$('#btnVolunteerSaveBtn').on('click', function() { // on click of save button
debugger;
if (document.getElementById('RadioNo').checked) { //ID of radio button NO
var checking = $('#Donation').val(); //ID of textbox from where the value is to be taken if RadioButton No is selected
if (checking == "") {
//if nothing is entered, stop from saving in DB
}
else {
var x = $('#Donation').val(); //ID of textbox from where the value is to be taken if RadioButton No is selected
var jsonObject = {
"textValue": x,
"isRadioSelected": "true" // show the radio is selected
};
$.ajax({
url: '#Url.Action("AddVolunteer", "VolunteerInfo")',
data: JSON.stringify(jsonObject),
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
error: function (response) {
alert(response.responseText);
},
success: function (response) {
alert(response);
}
});
}
}
else {
var jsonObject2 = {
"textValue": $('#GetNames').val(),
"isRadioSelected": "false" // show the radio is not selected
};
$.ajax({
url: '#Url.Action("AddVolunteer", "VolunteerInfo")',
data: JSON.stringify(jsonObject2),
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
error: function (response) {
alert(response.responseText);
},
success: function (response) {
alert(response);
}
});
}
});
})
</script>
In my controller:
[HttpPost]
public ActionResult AddVolunteer(VolunteerInfo volunteerInfo)
{
if (volunteerInfo.isRadioSelected)
{
//something
}
else
{
//something
return View();
}
1) Client calls to DonationValue post method with name paramter
e.g. name="abc"
[HttpPost]
public string DonationValue(string name = null) // name = "abc"
{
return name; //Trying to pass this value above
}
This returned value to be stored in client side say variable retunedDonationValue
If you don't pass any name parameter then above post method does return empty string then just set retunedDonationValue = ''
2) Now you have to pass above retunedDonationValue to your post method in posted json object like
var jsonObject =
{
"Name" = "YourName",
"BirthdayDateTime" = "YourBirthdayDateTime",
"Address" = "YourAddress",
"PhoneNumber" = "YourPhoneNumber",
"EmailAddress" = "YourEmailAddress",
"OccasionsID" = "YourOccasionsID",
"DonationForWhom" = retunedDonationValue //Note here
}
3) And pass this post data to http call to AddVolunteer
$.ajax({
url: '#Url.Action("AddVolunteer", "VolunteerInfo")',
data: JSON.stringify(jsonObject),
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
error: function (response) {
alert(response.responseText);
},
success: function (response) {
alert(response);
}
});
4) And your action method is look like
[HttpPost]
public ActionResult AddVolunteer(VolunteerInfo viewModel)
{
if (!ModelState.IsValid)
{
return View("AddVolunteer", viewModel);
}
var volunteer = new VolunteerInfo()
{
Name = viewModel.Name,
BirthdayDateTime = viewModel.BirthdayDateTime,
Address = viewModel.Address,
PhoneNumber = viewModel.PhoneNumber,
EmailAddress = viewModel.EmailAddress,
OccasionsID = viewModel.OccasionsID,
DonationForWhom = viewModel.DonationForWhom
};
if (!string.IsNullOrEmpty(volunteer.DonationForWhom))
{
_context.VolunteerInfos.Add(volunteer);
_context.SaveChanges();
}
return View(viewModel);
}

Pass array from client side to service side c#

I am calling a javascript function on button click using onclientclick with below function.
function addValues() {
debugger;
var arrValue = [];
var hdnValue = document.getElementById("hdn").value;
var strValue = hdnValue.split(',');
for (var i = 0; i < strValue.length; i++) {
var ddlValue = document.getElementById(strValue[i]).value;
arrValue.push(ddlValue);
}
}
arrValue array will have all the required values and how can I move this array values to server side for further process.
Update 1:
HTML:
function addValues() {
debugger;
var arrddlValue = [];
var hdnddlValue = document.getElementById("hdnDDL").value;
var strddlValue = hdnddlValue.split(',');
for (var i = 0; i < strddlValue.length; i++) {
var ddlValue = document.getElementById(strddlValue[i]).value;
arrddlValue.push(ddlValue);
}
}
$.ajax({
url: '',
data: { ddlArray: arrddlValue },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
},
error: function (x, e) {
}
});
Code:
protected void btnSort_Click(object sender, EventArgs e)
{
try
{
if (Request["ddlArray[]"] != null)
{
string[] arrValues = Array.ConvertAll(Request["ddlArray[]"].ToString().Split(','), s => (s));
}
}
}
If your framework is ASP.Net you can pass it by $.ajax, I am passing array like:
$.ajax({
url: '',
data: { AbArray: arrValue },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
},
error: function (x, e) {
}
});
and get it in Back-end like:
if (request["AbArray[]"] != null)
{
int[] arrValues = Array.ConvertAll(request["AbArray[]"].ToString().Split(','), s => int.Parse(s));
}
suppose array is int.
the above sample is using Generic-Handler.
if you want to use webmethod do something like:
[WebMethod(EnableSession = true)]
public static void PassArray(List<int> arr)
{
}
and Ajax would be like:
function addValues() {
debugger;
var arrddlValue = [];
var hdnddlValue = document.getElementById("hdnDDL").value;
var strddlValue = hdnddlValue.split(',');
for (var i = 0; i < strddlValue.length; i++) {
var ddlValue = document.getElementById(strddlValue[i]).value;
arrddlValue.push(ddlValue);
}
var jsonVal = JSON.stringify({ arr: arrValue });
$.ajax({
url: 'YourPage.aspx/PassArray',
data: jsonVal,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
},
error: function (x, e) {
}
});
}
Change Ajax Url as your PassArray address which mean YourPage.aspx should be change to page name which have PassArray in it's code-behind.
For more info Read This.
If you are using Asp.net WebForm Application,
Approach 1 : you can store your array value in a hidden input control and retrieve the saved data in your c# coding.
Approach 2 : define web method in your server side c# code and pass this javascript array value as ajax call.
link for Approach 1 : https://www.aspsnippets.com/Articles/Pass-JavaScript-variable-value-to-Server-Side-Code-Behind-in-ASPNet-using-C-and-VBNet.aspx
link for Approach 2 : https://www.aspsnippets.com/Articles/Send-and-receive-JavaScript-Array-to-Web-Service-Web-Method-using-ASP.Net-AJAX.aspx
I would "stringify" the array by imploding it with a special char unlikely to appear in my values (for example: §), and then with the help of jQuery.ajax() function, I will send it to the backend (ASP.NET MVC) action method:
$.ajax({
url : 'http://a-domain.com/MyController/MyAction',
type : 'POST'
data : 'data=' + myStringifiedArray;
});
My backend would be something like this (in MyController class):
[HttpPost]
public ActionResult MyAction(string data)
{
string[] arrValue = data.Split('§');
...
}
UPDATE
For ASP.NET forms, the ajax request would be:
$.ajax({
url : 'http://a-domain.com/MyPage.aspx/MyMethod',
type : 'POST'
data : 'data=' + myStringifiedArray;
});
And the backend would be something like this:
[System.Web.Services.WebMethod]
public static void MyMethod(string data)
{
string[] arrValue = data.Split('§');
...
}
You will find a more precise explanation here: https://www.aspsnippets.com/Articles/Call-ASPNet-Page-Method-using-jQuery-AJAX-Example.aspx

Posting Array and Form Data to Controller - MVC Ajax

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

Categories