I using .net core. Have this class:
public class SentEmailItem
{
public SentEmailItem()
{
Attachments = new List<AttachmentItem>();
}
public long PKID { get; set; }
public string EmailTo { get; set; }
public string EmailFrom { get; set; }
public string Cc { get; set; }
public string Bcc { get; set; }
public string Body { get; set; }
public string Subject { get; set; }
public List<string> EmailToList => EmailTo.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
public List<string> CcList => (Cc ?? string.Empty).Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
public List<string> BccList => (Bcc ?? string.Empty).Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
public List<AttachmentItem> Attachments { get; set; }
}
And this method in controller:
[HttpPost]
public JsonResult SendEmail(SentEmailItem item)
{
EmailHelper.SendEmailAsync(item);
return SuccessJsonResult();
}
But when called this method from ajax by this code:
$.ajax({
type: "POST",
url: self.sendEmailUrl,
contentType: "application/json",
dataType: "json",
data: JSON.stringify({ item: emaiItem })
}).done(function (json) {
App.unblockUI();
if (json.HasErrors) {
var errorsHtml = $.map(json.Errors, function (x) { return "" + x.ErrorMessage + "<br/>"; }).join("");
UIToastr.ShowMessage('error', 'Error', errorsHtml);
return;
}
self.sendEmailCompleted(json);
});
I can't get data in my controller method. All data have null value. But in emaiItem placed in js value looks like:
Bcc : "Testmail#mail.com"
Body : "test body"
Cc : "Testmail#mail.com"
EmailFrom : "just3f#mail.com"
EmailTo : "Testmail#mail.com"
Subject : "Test subject"
It seems like emaiItem is already an object like this -
var emaiItem = {Bcc : "Testmail#mail.com",
Body : "test body",
Cc : "Testmail#mail.com",
EmailFrom : "just3f#mail.com",
EmailTo : "Testmail#mail.com",
Subject : "Test subject"};
If so, it could just use JSON.stringify(emaiItem). Otherwise, you can hard-code the above emaiItem, and see those values populated at server-side.
$.ajax({
...
data: JSON.stringify(emaiItem)
}).done(function (json) {
...
});
Solution
Replace with JSON.stringify(emaiItem), and use [FromBody] attribute to force model binder to bind data from the request body.
[HttpPost]
public JsonResult SendEmail([FromBody]SentEmailItem item)
{
}
Have you tried debugging your c# code to see if the back-end api is being hit? That would be a good place to start if not.
Related
Im trying to pass an Id and object of picList to the controller and it shows up null. I've looked at all the other SO solutions and changed my code to what they said and Im still getting null for both values in the controller.
So I've even tried to change the data that is being sent to the controller as such to see if that made any difference and it didn't.
in ajax call i changed the data to such
data: {"Name": "Adam"},
and added this to the controller and still nothing is getting passed.
UnitImages(string Name,..
here is what the JSON.stringify(data) looks like.
View Model
public class FileViewModel
{
public FileViewModel()
{
UnitPicturesList = new List<UnitPictures>();
}
public IList<IFormFile> Files { get; set; }
[Required]
public int AuctionId { get; set; }
public string FileLocation { get; set; }
public List<UnitPictures> UnitPicturesList { get; set; }
}
model
public class UnitPictures
{
public long ImageId { get; set; }
public string FileName { get; set; }
public string FileLocation { get; set; }
public int SortOrder { get; set; }
}
controller
[HttpPost]
public ActionResult UnitImages(long auctionId, List<UnitPictures> picList)
{ ...
}
Ajax call
function UpdateImages(auctionId, picList) {
var data = { auctionId: auctionId, picList: picList };
console.log(JSON.stringify(data));
$.ajax({
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
url: '/PhotoUploader/UnitImages',
data: JSON.stringify(data),
success: function(data){
if(data.Result == 1) {
alert("images where successfully updated.");
}else {
alert('images where successfully updated.');
}
},
error: function() {
alert("The images were not updated because of a problem.")
}
});
}
Asp.net core MVC default binding value from form, Here you can try to add [FromBody] attribute on your parameter to change the resource to bind value from body.
[HttpPost]
public ActionResult UnitImages([FromBody]string Name)
{ ...
}
Model details you can refer to Model Binding.
Try using a class that match the posted model. Something like this:
public class UnitPictures_ViewModel
{
public int AuctionId {get;set;}
public List<UnitPictures> PicList { get; set; }
}
public class UnitPictures
{
public long ImageId { get; set; }
public string FileName { get; set; }
public string FileLocation { get; set; }
public int SortOrder { get; set; }
}
I´m having issues passing an array of JSON objects to an MVC controller in ASP.Net core 3. The JSON object is built from a CSV file and passed through an AJAX call. The correct action is called but the object received is always null.
JS:
async function updateData(){
var obj = await getData();
$.ajax({
type: "POST",
contentType: "application/json",
url: "/admin/metric/Update",
data: obj,
dataType: 'json',
success: function (data) {
console.log("SUCCESS : ", data);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
async function getData(){
var metric = {};
var metrics = [];
var response = await fetch('https://bloburi.net/source/file.csv');
var data = await response.text();
var table = data.split('\n').slice(1);
table.forEach(row => {
var columns = row.split(',');
metric["FirstName"] = columns[0];
metric["LastName"] = columns[1];
metric["Email"] = columns[2];
metric["AverageHandleTime"] = columns[3];
metric["AverageFollowUp"] = columns[4];
metric["AverageHold"] = columns[5];
metric["Date"] = columns[6];
metrics.push(JSON.stringify(metric));
});
console.log(metrics);
return metrics;
}
Models:
public class MetricBase
{
[Required]
public string Date { get; set; }
public double AverageHandleTime { get; set; }
public double AverageHold { get; set; }
public double AverageFollowUp { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class MetricModel
{
public IEnumerable<MetricBase> MetricBase { get; set; }
}
Controller:
[HttpPost]
public IActionResult Update([FromBody]MetricModel obj)
{
return Json(new { obj });
}
I think the issue may be on how I'm deffining the class that is receiving the JSON, but I've tried multiple things like deffining MetricBase as a List<> or straight up as an array in MetricModel, but it doesn't seem to work.
Any help is appreciated!
You adding the stringify item inside array via code
metrics.push(JSON.stringify(metric));
instead of stringify the whole array. Change the line to
metrics.push(metric);
and data: obj, to
data: JSON.stringify(obj),.
With the mentioned change, the $.ajax sends the whole array. Also change the action to
public IActionResult Update([FromBody]IEnumerable<MetricBase> obj)
I've a problem with sending data form the browser to an API on my server by an ajax request to the server (method is PUT). Here is my JavaScript code:
var json = JSON.stringify({
StemType: {
ID: parseInt(this.dataset.id),
Type: this.dataset.type,
GebruikerID: "#(Model.DeTopic.Gebruiker.Id)"
},
Punten: parseInt(this.dataset.punten),
GestemdeGebruikerID: "#(Model.AangemeldeGebruiker)"
});
$.ajax({
url: "../Stem/Toevoegen",
type: "PUT",
data: json,
success: function (returnData) {
// my code
}
});
This is the json code in the variable json:
{
"StemType": {
"ID": 24731,
"Type": "Topic",
"GebruikerID": "539e6078"
},
"Punten": 1,
"GestemdeGebruikerID": "3aedefab"
}
And here is the C# code on the server.
public class StemController : ApiController
{
[HttpPost]
[Authorize]
[Route("Stem/Toevoegen")]
public void Toevoegen([FromBody]Stem stem)
{
Console.WriteLine(stem.ToString());
}
}
Here is the class Stem:
public class Stem
{
public StemType StemType { get; set; }
public int Punten { get; set; }
public string GestemdeGebruikerID { get; set; }
}
public class StemType
{
public int ID { get; set; }
public Type Type { get; set; }
public string GebruikerID { get; set; }
}
But if I debug my code on the server, I've got this:
Can anyone help me?
I've found two possible ways:
Don't stringify it for send as an object.
Add contentType: "application/json" for Json code.
Hello i want to add data on database in sql but i can't find how to do this using javascript,i work on visual studio
You can use Javascript to pass data back to your .NET MVC C# Controller method
var myViewModel = {};
var team= {};
team.TeamID = 1234;
team.TeamName = "Test Team";
myViewModel.Team= team;
var teamPlayerList = [];
var player1= {};
player1.id= "1";
player1.Name = "Patrick";
var player2 = {};
player2.id= "2";
player2.Name = "Padraig";
teamPlayerList.push(player1);
teamPlayerList.push(player2 );
myViewModel.TeamPlayerList = teamPlayerList;
$.ajax(
{
url: 'Team/Create',
data: JSON.stringify({teamViewModel : myViewModel}),
contentType: 'application/json',
dataType: 'json',
type: 'POST',
success: function (data) {
alert("success");
},
error: function () { alert('error'); }
});
On the backend in the C# you will need A controller class, and some C# classes to hold the data you pass in from javascript
public class Team
{
public long TeamID { get; set; }
public string TeamName { get; set; }
}
public class TeamPlayer
{
public string id{ get; set; }
public string Name { get; set; }
}
A ViewModel
public class TeamViewModel
{
public Team Team { get; set; }
public IList<TeamPlayer> TeamPlayerList { get; set; }
}
The controllers method will be something like this
public class TeamController : Controller
{
[HttpPost]
public ActionResult Create(TeamViewModel teamViewModel)
{
//USE HERE TO EXTRACT DATA PASSED IN
var myTeam = teamViewModel.Team;
var teamPlayerList = teamViewModel.TeamPlayerList;
//call your db insert class/code and use values passed in
return Content("success");
}
Not sure if it's just the time of day, lack of coffee or over indulgence of sugar from last night. Besides that I'm trying to get this working. I do not want to change / modify / add a new web service method.
I have an asmx web service:
public UserLogin Login(UserLogin p_objUserLogin)
{
}
I need to hook a JQuery ajax call up to that. The UserLogin object is not that complex:
public class UserLogin
{
public UserLogin();
public string Privileges { get; set; }
public string ClientCodeID { get; set; }
public UserDetails User { get; set; }
public string UserLoginMessage { get; set; }
public bool Valid { get; set; }
}
The UserDetails object is quite large, and includes a lot more data. (Hopefully I don't need to build the entire object tree to get this to work).
public class UserDetails
{
public string CellPhone { get; set; }
public string Email { get; set; }
public string EncryptedPassword { get; set; }
public string FirstName { get; set; }
public string FullName { get; }
public string Initials { get; set;
public bool InService { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public byte[] Signature { get; set; }
public string SimCard { get; set; }
public int UserID { get; set; }
public string UserName { get; set; }
public SecurityRole UserSecurityRole { get; set; }
public Workgroup UserWorkgroup { get; set; }
}
The script I'm playing around with:
function CallService() {
var p_objUserLogin = {};
p_objUserLogin['ClientCodeID'] = "Test";
var DTO = { 'p_objUserLogin': p_objUserLogin };
$.ajax({
type: "POST",
url: "UtilityServices2006.asmx/Login",
data: JSON.stringify(DTO),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (msg) {
alert(msg);
},
error: function (req, status, error) {
alert(req + ", " + status + ", " + error);
},
complete: function (req, status) {
alert(req + ", " + status);
}
});
}
Any help would be quite amazing.
Ensure your webservice class and method are decorated to handle incoming ajax/json requests:
[ScriptService]
public class MyService: WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public UserLogin Login(UserLogin p_objUserLogin)
{
}
}
I'm not familiar with the notation you're using to configure your payload object (p_objUserLogin['ClientCodeID'] = "Test";). I've usually used slightly different notation:
p_objUserLogin.ClientCodeID = 'Test';
However, that might be a red herring - I'm not a JS-objects expert, so your notation may be perfectly valid.
Finally, I'm not sure if JS will automatically convert your object to JSON (var DTO = { 'p_objUserLogin': p_objUserLogin };). I use the json2 library to explicitly serialize JS objects to JSON:
var DTO = { 'p_objUserLogin': JSON.stringify(p_objUserLogin) };
Hope this helps you nail down the issue.