Parse string to object - javascript

i have created a table in javascript :
var global = [];
function GetValues() {
debugger;
var myList = $("#multiSelect");
var yy = $("#article").val();
var Selectedelement = $("#quantiCommande").val();
myList.append('<option value=' + Selectedelement + '>' + Selectedelement + " " + yy + '</option>');
global.push({ "id": yy, "qte": Selectedelement });
}
i want now to send table global to the controller and this the code of method javasript that send table glabal to the controller:
and this is the form of my table in javascript:enter image description here
function Test() {
var NumCommande = $("#NumCommande").val();
var client = $("#clientc").val();
debugger;
$.ajax({
url: "/Commande/Ajoutercommande?NumCommande=" + NumCommande + "&client=" + client + "&global=" + global, // /Controlleur/Action
type: "POST",
dataType: 'text',
//data : {Nom: nom},
success: function (responseText) {
debugger;
if (responseText == "True") {
alert("Succes");
}
else {
alert("error");
}
}
});
}
and this is my controller methode i need to display the element of my table global
public Boolean Ajoutercommande(string NumCommande, int client, Object global)
{
CRUDEntities db = new CRUDEntities();
Commande c = new Commande();
c.NumCommande = NumCommande;
c.Quantité = client;
Console.Write(global);
db.Commande.Add(c);
db.SaveChanges();
return true;
return true;
}
can someone help me to fix this code and thank you.

I would recommend to create one single object parameter.
Define your datacontract
public class TableContent
{
public int id { get; set; }
public string qte { get; set; }
}
public class AjourtercommandParam
{
public string NumCommande { get; set; }
public int client { get; set; }
public TableContent[] global { get; set; }
}
then, in your controller (WebApi controller, right?)
[HttpPost]
[Route("Commande/Ajoutercommande")]
public async Task<IHttpActionResult> Ajoutercommand(AjoutercommandParam param)
{
if(ModelState.IsValid == false)
{
return BadRequest(ModelState);
}
try
{
var result = await DataLayerService.AjouterCommand(param);
return Ok(result);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
Post your data in the data section of the ajax call.
$.ajax({
url: "/Commande/Ajoutercommande",
type: "POST",
dataType: 'json',
data : {
"NumCommande": NummCommande,
"client" : client,
"global" : global
},
success: function (responseText) {
debugger;
if (responseText == "True") {
alert("Succes");
}
else {
alert("error");
}
}
});

Related

Parameter sent to ASP NET Core Controller from AJAX call is null if it's too large?

I have AJAX code in my page which calls an ASP.NET Core controller. The code sends a list of objects to the controller. When the list is short enough, say 8 objects, the fundFindingsGridRows parameter is properly set to the data, however, when longer, this parameter is null.
I have tried setting several things in my Startup.cs but nothing has worked. Is there some other setting that I can configure to get this to accept larger amounts of data? Is there another issue other than size at play here?
Startup.cs (pertinent code):
services.AddMvc(options =>
{
options.MaxModelBindingCollectionSize = 100000;
});
services.Configure<FormOptions>(options =>
{
options.ValueCountLimit = int.MaxValue;
options.ValueLengthLimit = int.MaxValue;
options.MultipartHeadersLengthLimit = int.MaxValue;
});
services.Configure<IISServerOptions>(options =>
{
options.MaxRequestBodySize = int.MaxValue;
});
Javascript AJAX code:
var DATA = new Array();
var grid = $("#V3FundFindingsByBuildingGrid").data("kendoGrid");
var dataTable = grid.dataSource;
$.each(grid.items(), function (index, item) {
var id = $(item).data('uid');
var dataItem = dataTable.getByUid(id);
var building = {};
building.PANumber = dataItem.PANumber,
building.employerNo = dataItem.employerNo,
building.billToEntityNo = dataItem.billToEntityNo,
building.accountNo = dataItem.AccountNo,
building.revisionDateExists = #Model.revisionDateExists.ToString().ToLower(),
building.settlement = false,
building.health = dataItem.Health,
building.pension = dataItem.Pension,
building.annuity = dataItem.Annuity,
building.legal = dataItem.Legal,
building.training = dataItem.Training,
building.joint = dataItem.Joint,
building.four01k = dataItem.Four01k,
building.healthInterest = dataItem.HealthInterest,
building.pensionInterest = dataItem.PensionInterest,
building.annuityInterest = dataItem.AnnuityInterest,
building.legalInterest = dataItem.LegalInterest,
building.trainingInterest = dataItem.TrainingInterest,
building.jointInterest = dataItem.JointInterest,
building.four01kInterest = dataItem.Four01kInterest
DATA.push(building);
});
var fundFindingsGridRows = JSON.stringify(DATA);
$.ajax({
type: "POST",
url: "/PayrollAudit/SaveFundFindings",
data: fundFindingsGridRows,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$('#FindingsByBuildingDiv').html(response);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
Controller Action:
[RequestSizeLimit(100_000_000)]
public IActionResult SaveFundFindings([FromBody]List<FundFindingsGridRow> fundFindingsGridRows)
{...}
Data from the Header:
Parsed payload snippet:
So I found away to solve this issue. What I did was to not send the data to the controller as JSON, and instead of as an array of objects. I also removed the contentType and dataType settings from the AJAX call, and changed the data setting:
var DATA = new Array();
var grid = $("#V3FundFindingsByBuildingGrid").data("kendoGrid");
var dataTable = grid.dataSource;
$.each(grid.items(), function (index, item) {
var id = $(item).data('uid');
var dataItem = dataTable.getByUid(id);
var FundFindingsGridRow = {};
FundFindingsGridRow.PANumber = dataItem.PANumber,
FundFindingsGridRow.employerNo = dataItem.employerNo,
FundFindingsGridRow.billToEntityNo = dataItem.billToEntityNo,
FundFindingsGridRow.accountNo = dataItem.AccountNo,
FundFindingsGridRow.revisionDateExists = #Model.revisionDateExists.ToString().ToLower(),
FundFindingsGridRow.settlement = false,
FundFindingsGridRow.health = dataItem.Health,
FundFindingsGridRow.pension = dataItem.Pension,
FundFindingsGridRow.annuity = dataItem.Annuity,
FundFindingsGridRow.legal = dataItem.Legal,
FundFindingsGridRow.training = dataItem.Training,
FundFindingsGridRow.joint = dataItem.Joint,
FundFindingsGridRow.four01k = dataItem.Four01k,
FundFindingsGridRow.healthInterest = dataItem.HealthInterest,
FundFindingsGridRow.pensionInterest = dataItem.PensionInterest,
FundFindingsGridRow.annuityInterest = dataItem.AnnuityInterest,
FundFindingsGridRow.legalInterest = dataItem.LegalInterest,
FundFindingsGridRow.trainingInterest = dataItem.TrainingInterest,
FundFindingsGridRow.jointInterest = dataItem.JointInterest,
FundFindingsGridRow.four01kInterest = dataItem.Four01kInterest
DATA.push(FundFindingsGridRow);
});
$.ajax({
type: "POST",
url: "/PayrollAudit/SaveFundFindings",
data: { 'fundFindingsGridRows': DATA },
success: function (response) {
$('#FindingsByBuildingDiv').html(response);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
Not sure what the issue was with the JSON. If someone can let me know, I'd appreciate it in case I run across an instance where JSON is required in the future!
Below is a work demo that can send the data to the controller as JSON, you can refer to it.
Student:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Name2 { get; set; }
public string Name3 { get; set; }
public string Name4 { get; set; }
public string Name5 { get; set; }
public string Name6 { get; set; }
public string Name7 { get; set; }
public string Name8 { get; set; }
public string Name9 { get; set; }
public string Name10 { get; set; }
}
HomeController:
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index([FromBody] List<Student> student)
{
return View();
}
}
Index view:
<button onclick="postdata1()">submit(jsondata)</button>
#section scripts{
<script type="text/javascript">
function postdata1() {
var a = new Array();
for (var i = 0; i < 100000; i++) {
var indexViewModel = {};
indexViewModel.Id = i;
indexViewModel.Name = "name" + i;
indexViewModel.Name2 = "name2" + i;
indexViewModel.Name3 = "name3" + i;
indexViewModel.Name4 = "name4" + i;
indexViewModel.Name5 = "name5" + i;
indexViewModel.Name6 = "name6" + i;
indexViewModel.Name7 = "name7" + i;
indexViewModel.Name8 = "name8" + i;
indexViewModel.Name9 = "name9" + i;
indexViewModel.Name10 ="name10" + i;
a.push(indexViewModel);
}
var data = JSON.stringify(a);
$.ajax({
type: "POST",
url: '/home/Index',
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
}).done(function (data) {
});
}
</script>
}
result:

large file attachment via Angularjs

Below code has been generated and connected to a controller called "streaming" in .net core. The code works well and attaches large files perfectly.
The code needs to be used in another html page to upload files for different purpose. However, when upload button is pressed, below error is displayed:
Failed to load resource: the server responded with a status of 400 (Bad Request)
This is the case that if I attach a file from the original page, the process gets completed and then I can attach any file from the copied page!
But if I close the browser and try to attach a file from the copied page the error is displayed.
<div class="panel-body" ng-app="myApp">
#*Attachment*#
<div ng-app="myApp">
<div ng-controller="myCtrl">
<div>
#if (ViewBag.Attachments != null)
{
foreach (var a in ViewBag.Attachments)
{
var id = #a.AttachmentId;
#lastattachid = id;
<div class="row">
<div class="col-xs-12 left">
<a asp-action="Download" asp-route-path="#a.FilePath\\#a.FileName">#a.FileName</a>
<div style=" position: absolute;top: 2px;right: 2px;">
#if (ViewBag.recepient.Equals(#a.CreatedBy))
{
var FilePath = #a.FilePath.Replace("\\", "\\\\");
<a onclick='deleteattachment(#a.AttachmentId, "#a.FileName", "#FilePath")'>✘</a>
}
</div>
</div>
</div>
}
}
</div>
<hr />
<div>
<div>
<div>
<input name="attachedfile" type="file" file-model="attachedfile" />
</div>
</div>
<br />
<div>
<button ng-click="uploadAttachment()">Upload</button>
</div>
</div>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
<script>
var Attachment = (function () {
function Attachment(customer, invoice, name, dwg, attachedfile) {
this.attachmentid = #lastattachid + 1;
this.customer = customer;
this.jobInv = invoice;
this.jobName = name;
this.jobDwg = dwg;
this.path = "\\#ViewBag.customerId\\" + invoice + ";" + name + ";" + dwg + "\\";
this.fileName = attachedfile.name;
this.attachedfile = attachedfile;
}
return Attachment;
}());
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function () {
scope.$apply(function () {
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.service('attachmentService', ['$http', function ($http) {
this.uploadAttachment = function (attachment) {
var fd = new FormData();
fd.append('AttachmentId', attachment.attachmentid);
fd.append('Customer', attachment.customer);
fd.append('JobInv', attachment.jobInv);
fd.append('JobName', attachment.jobName);
fd.append('JobDwg', attachment.jobDwg);
fd.append('Name', attachment.fileName);
fd.append('Path', attachment.path);
fd.append('attachedfile', attachment.attachedfile);
return $http.post('/Streaming/Upload', fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
});
};
}]);
myApp.controller('myCtrl', ['$scope', 'attachmentService', function ($scope, attachmentService) {
$scope.uploadAttachment = function () {
$scope.showUploadStatus = false;
$scope.showUploadedData = false;
var attachment = new Attachment("#customerid","#inv", " ", " ", $scope.attachedfile);
attachmentService.uploadAttachment(attachment).then(function (response) { // success
if (response.status === 200) {
var inv = "#inv";
inv = inv.replace("&", "%26");
var job = "#job";
job = job.replace("&", "%26");
var dwg = "#dwg";
dwg = dwg.replace("&", "%26");
window.location.href = "/Quote/Details/#ViewBag.customerId?quoteno=" + inv;
}
},
function (response) { // failure
$scope.uploadStatus = "Attachment upload failed with status code: " + response.status;
$scope.showUploadStatus = true;
$scope.showUploadedData = false;
$scope.errors = [];
$scope.errors = parseErrors(response);
});
};
}]);
function parseErrors(response) {
var errors = [];
for (var key in response.data) {
for (var i = 0; i < response.data[key].length; i++) {
errors.push(key + ': ' + response.data[key][i]);
}
}
return errors;
}
</script>
Updated:
Server-side code is as below:
[HttpPost]
[DisableFormValueModelBinding]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Upload()
{
if (string.IsNullOrEmpty(userManager.GetUserName(User)))
return RedirectToAction(actionName: "Login", controllerName: "Account");
if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
{
return BadRequest($"Expected a multipart request, but got {Request.ContentType}");
}
// Used to accumulate all the form url encoded key value pairs in the
// request.
var formAccumulator = new KeyValueAccumulator();
string targetFilePath = Directory.GetCurrentDirectory() + "\\wwwroot\\Attachment";
string fileName = "";
var boundary = MultipartRequestHelper.GetBoundary(
MediaTypeHeaderValue.Parse(Request.ContentType),
_defaultFormOptions.MultipartBoundaryLengthLimit);
var reader = new MultipartReader(boundary, HttpContext.Request.Body);
var section = await reader.ReadNextSectionAsync();
while (section != null)
{
ContentDispositionHeaderValue contentDisposition;
var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);
if (hasContentDispositionHeader)
{
if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
{
using (var targetStream = System.IO.File.Create(targetFilePath + fileName))
{
await section.Body.CopyToAsync(targetStream);
_logger.LogInformation($"Copied the uploaded file '{targetFilePath + fileName}'");
}
}
else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
{
// Content-Disposition: form-data; name="key"
//
// value
// Do not limit the key name length here because the
// multipart headers length limit is already in effect.
var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
var encoding = GetEncoding(section);
using (var streamReader = new StreamReader(
section.Body,
encoding,
detectEncodingFromByteOrderMarks: true,
bufferSize: 1024,
leaveOpen: true))
{
// The value length limit is enforced by MultipartBodyLengthLimit
var value = await streamReader.ReadToEndAsync();
value = value.Replace("&", "&");
if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
{
value = String.Empty;
}
formAccumulator.Append(key, value);
if (key.Equals("Path"))
{
targetFilePath += value;
Directory.CreateDirectory(targetFilePath);
}
if (key.Equals("Name"))
fileName = value;
if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit)
{
throw new InvalidDataException($"Form key count limit {_defaultFormOptions.ValueCountLimit} exceeded.");
}
}
}
}
// Drains any remaining section body that has not been consumed and
// reads the headers for the next section.
section = await reader.ReadNextSectionAsync();
}
// Bind form data to a model
var attachment = new AttachFile();
var formValueProvider = new FormValueProvider(
BindingSource.Form,
new FormCollection(formAccumulator.GetResults()),
CultureInfo.CurrentCulture);
var bindingSuccessful = await TryUpdateModelAsync(attachment, prefix: "",
valueProvider: formValueProvider);
if (!bindingSuccessful)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
}
var user = userManager.GetUserName(User);
// Add attachmnet to a jason file
// ...
var uploadedData = new UploadedData()
{
Invoice = attachment.JobInv,
Name = attachment.JobName,
Dwg = attachment.JobDwg,
FileName = attachment.FileName,
FilePath = targetFilePath,
CreatedBy = user,
CreatedDate = DateTime.Now
};
return Json(uploadedData);
}
public class AttachFile
{
public int AttachmentId { get; set; }
public string Customer { get; set; }
public string JobInv { get; set; }
public string JobName { get; set; }
public string JobDwg { get; set; }
public string FileName { get; set; }
public string FilePath { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
}
public class UploadedData
{
public string Invoice { get; set; }
public string Name { get; set; }
public string Dwg { get; set; }
public string FileName { get; set; }
public string FilePath { get; set; }
public string Path { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
}

Can't pass a list of objects to the view using JSON

The data is passed from the controller to the view using AJAX call
but for some reason I am not able to retrieve it using JavaScript
the data shows an list on empty object!
public class Ville {
string wilPop { get; set; }// = null;
int identifiant { get; set; }// = -1;
bool affectedD { get; set; } //= false;
public Ville(string ewilPop, int eidentifiant, bool eaffectedD)
{
this.wilPop = ewilPop;
this.identifiant = eidentifiant;
this.affectedD = eaffectedD;
}
}
[Authorize]
[HttpPost]
public ActionResult GetWilByRegion(int? Wil)
{
if (Wil != null)
{
string wilPop = null;
int identifiant = -1;
bool affectedD = false;
//Get info from DB
List<city> ListWil = new List<city>();
ListWil = db.city.Where(m => m.idReg == Wil).OrderByDescending(m => m.population).ToList();
List<Ville> mylist = new List<Ville>();
foreach (city item in ListWil)
{
// Description in the DB
wilPop = item.city + " (" + item.population + ")";
// id value in the DB
identifiant = item.city_id;
// if checked or not
affectedD = CheckifWilAffected(item.city_id);
mylist.Add(new Ville(wilPop, identifiant, affectedD));
}
return Json(mylist, "Ville");
}
else return Json("Error");
}
mylist is not empty, it contains all the data (after debugging the controller)
This is my AJAX call :
$.ajax({
url: url,
data: { Wil: _idr },
cache: false,
type: "POST",
success: function (data) {
var markup = "";
for (var x = 0; x < data.length; x++) {
markup += '<input type=' + '"checkbox"' + ' name=' + data[x].wilPop + ' value=' + data[x].identifiant + '>' + data[x].wilPop + '</input>' + '<br/>';
}
$("#chWil").html(markup).show();
},
error: function () {
alert("Error - can't do the ajax call - please check your code..." );
}
});
}
You are getting an array of empty objects(without any properties) because your Ville class does not have any public properties.
You need to make your properties public
public class Ville
{
public string wilPop { get; set; }
public int identifiant { get; set; }
public bool affectedD { get; set; }
public Ville(string ewilPop, int eidentifiant, bool eaffectedD)
{
this.wilPop = ewilPop;
this.identifiant = eidentifiant;
this.affectedD = eaffectedD;
}
}
Now the JavaScript serializer will be able to use the values of those properties when creating a JSON string representation of your list.
I personally like to use PascalCasing for class property names.( WilPop instead of wilPop)

Not able to load the Gridview on Load

I am not able to load the gridview on page load. It keeps giving me
Uncaught TypeError: Cannot read property 'length' of undefined.
I have mnetioned the code and the handler beneath. Please help me solve the issue. The issue happens in the Jquery.
<script type="text/javascript">
$(document).ready(function () {
BindGridView();
});
function BindGridView() {
$.ajax({
type: "POST",
url: "../Pm/uc/G.ashx/GetMailDetail",
contentType: "application/json;charset=utf-8",
data: {},
dataType: "json",
success: function (data) {
if (data.d.length > 0) {
$("#grdDemo").append("<tr><th>Username</th></tr>");
for (var i = 0; i < data.d.length; i++) {
$("#grdDemo").append("<tr><td>" +
data.d[i].Username + "</td> <td>");
}
}
},
error: function (result) {
}
});
}
</script>
<asp:GridView ID="grdDemo" runat="server">
</asp:GridView>
This is in the Handler.( You can replace the query with anything.)
public void ProcessRequest(HttpContext context)
{
//int mailid = int.Parse(context.Request["mid"]);
//var detail = GetMailDetail(mailid);
var detail = GetMailDetail();
if (detail != null)
{
context.Response.ContentType = "application/json";
string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(detail);
context.Response.Write(json);
}
else
{
context.Response.StatusCode = 404;
}
}
//protected object GetMailDetail(int mailid)
protected object GetMailDetail()
{
List<DetailsClass> Detail = new List<DetailsClass>();
Connection Con = new Connection();
String Connection = Con.Active_Connection();
SqlConnection con = new SqlConnection(Connection);
con.Open();
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("select Sp4_Txt from Sp4", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dtGetData = new DataTable();
da.Fill(dtGetData);
foreach (DataRow dtRow in dtGetData.Rows)
{
DetailsClass DataObj = new DetailsClass();
DataObj.Username = dtRow["Sp4_Txt"].ToString();
Detail.Add(DataObj);
}
return Detail.ToArray();
}
public class DetailsClass //Class for binding data
{
public string Username { get; set; }
}
public bool IsReusable
{
get
{
return false;
}
}
}
Cannot read property 'length' of undefined.
This error is coming because you are accessing the data.d without checking data and accessing data.d.length without checking data.d
Do something like this:
if(data){
if(data.d){
if (data.d.length > 0) {
$("#grdDemo").append("<tr><th>Username</th></tr>");
for (var i = 0; i < data.d.length; i++) {
$("#grdDemo").append("<tr><td>" +
data.d[i].Username + "</td> <td>");
}
}
}
}

JSON data null in controller

I am working to send multiple email/SMS by selecting the checkbox. And When I am receiving in my javascript function it's getting with data. But when I pass it to action method record count shows but all data are null. Below is my code with screenshot here
Here it is my Model:
public class BulkEmailSendViewModel
{
public BulkEmailSendViewModel()
{
Candidates = new List<CandidateData>();
}
public List<CandidateData> Candidates { get; set; }
public string Body { get; set; }
public string Subject { get; set; }
}
public class CandidateData
{
public string Email { get; set; }
public string CandidateId { get; set; }
public string Phone { get; set; }
public string CandidateName { get; internal set; }
}
//Select all selected checkbox
$("#bulkAction").change(function () {
var ddlId = $("#bulkAction").val();//to get sms or email
var chk_arr = $('.checkCandidate:checkbox:checked');
var chklength = chk_arr.length;
var json = '';
$('.checkCandidate:checkbox:checked').each(function () {
if (this.checked) {
var Phone = $(this).attr("candidatePhone");
var CandidateId = $(this).attr("candidateId");
var Email = $(this).attr("candidatEmail");
var item = '{\"Phone\":\"' + Phone + '\","CandidateId\":\"' + CandidateId + '\",\"Email\":\"' + Email + '\",\"CandidateName\":\"\"},';
json += item;
}
});
json = "[" + json.substr(0, json.length - 1) + "]";
SendBulkEmail(json);
});
My Javascript:
function SendBulkEmail(jsonObj) {
alert(jsonObj);
if (jsonObj.length > 0) {
var send = "/Utility/Notifications/BulkEmail";
$(".modal-title").text("Send Email");
//var data = {
// Candidates: eval(jsonObj)
//};
$.get(send, { bulkEmailSendViewModel: eval(jsonObj) }, function (result) {
$("#C_modal_body").html("");
$("#C_modal_body").html(result);
});
}
else {
$.alert("Email not found for this candidate.");
// e.stopPropagation();
}
}
My Controller:
public PartialViewResult BulkEmail(List<CandidateData> bulkEmailSendViewModel)
{
BulkEmailSendViewModel bulkDetail = new BulkEmailSendViewModel();
return PartialView(bulkDetail);
}
Why my all values are null even I am getting in javascript function?
change your javascript codes to this:
$("#bulkAction").change(function () {
var ddlId = $("#bulkAction").val();//to get sms or email
var chk_arr = $('.checkCandidate:checkbox:checked');
var chklength = chk_arr.length;
var data = [];
$('.checkCandidate:checkbox:checked').each(function () {
if (this.checked) {
var Phone = $(this).attr("candidatePhone");
var CandidateId = $(this).attr("candidateId");
var Email = $(this).attr("candidatEmail");
var item = {Phone: Phone,
CandidateId: CandidateId,
Email : Email,
CandidateName : ""};
data.push(item);
}
});
SendBulkEmail(data);
});
and the SendBulkEmail to:
function SendBulkEmail(data) {
if (data.length > 0) {
var send = "/Utility/Notifications/BulkEmail";
$(".modal-title").text("Send Email");
//var data = {
// Candidates: eval(jsonObj)
//};
$.post(send, { bulkEmailSendViewModel: JSON.stringify(data) }, function (result) {
$("#C_modal_body").html("");
$("#C_modal_body").html(result);
});
}
else {
$.alert("Email not found for this candidate.");
// e.stopPropagation();
}
}
and finally:
[HttpPost]
public PartialViewResult BulkEmail(List<CandidateData> bulkEmailSendViewModel)
{
BulkEmailSendViewModel bulkDetail = new BulkEmailSendViewModel();
return PartialView(bulkDetail);
}
In your controller, I don't see any use of the bulkEmailSendViewModel input parameter.
Maybe, you could propagate the candidate list as follow:
public PartialViewResult BulkEmail(List<CandidateData> candidates)
{
BulkEmailSendViewModel bulkDetail=new BulkEmailSendViewModel();
bulkDetail.candidates = candidates;
return PartialView(bulkDetail);
}

Categories

Resources