Getting Null object array jquery post - javascript

I am new to Angular.js framework. I am getting data which i am further assigning to array using angular scope.
Modal.CS:
public class AppSetting1
{
public int lng_AppSettings { get; set; }
public string str_SettingName { get; set; }
public string str_SettingValue { get; set; }
public string str_Type { get; set; }
public AppSetting1(int _lng_AppSettings, string _str_SettingName, string _str_SettingValue, string _str_Type)
{
lng_AppSettings = _lng_AppSettings;
str_SettingName = _str_SettingName;
str_SettingValue = _str_SettingValue;
str_Type = _str_Type;
}
}
internal string GetAppSettings()
{
try
{
List<AppSetting1> objAppsettings = new List<AppSetting1>();
objAppsettings.Add(new AppSetting1(1,"Name1","Value1","Type"));
objAppsettings.Add(new AppSetting1(2, "Name2", "Value2", "Type2"));
return JsonConvert.SerializeObject(objAppsettings, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
}
catch (Exception ex)
{
throw ex;
}
}
Controller.CS:
[AuthCheckService, SessionCheckService]
[HandleModelStateException]
public string GetAppSettings()
{
try
{
ManageAppSettings accExec = new ManageAppSettings();
return accExec.GetAppSettings();
}
catch (Exception ex)
{
throw new ModelStateException(ex.Message, ex.InnerException);
}
}
[HttpPost]
public JsonResult SaveSettings(List<AppSetting1> AppSetting)
{
try
{
ManageAppSettings accExec = new ManageAppSettings();
return Json(AppSetting, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
throw new ModelStateException(ex.Message, ex.InnerException);
}
}
Angular.js:
(function () {
var app = angular.module('myAppSeetings', []);
app.controller('AppSettingsController', function ($scope) {
$scope.items = [];
$scope.SaveSettings = function () {
if (validate()) {
var token = $('[name=__RequestVerificationToken]').val();
var test = $scope.items;
$.ajax({
beforesend: showProgress(),
type: 'POST',
headers: { "__RequestVerificationToken": token },
url: getAppPath() + 'AppSettings/SaveSettings',
dataType: 'json',
data: { AppSetting: $scope.items },
success: function (result) {
if (result != "") {
//ShowSaveMessage(result);
//fetchData();
//$('#EditPopUp').css('display', 'none');
//$('#exposeMaskManageUser').css('display', 'none');
//clearForm();
}
else
ShowErrorPopup('An error has occurred. Please contact System Administrator.');
},
complete: hideProgress,
error: function (ex) {
ShowErrorPopup('An error has occurred. Please contact System Administrator.');
}
});
}
else {
ShowWarningMessage('Required fields must be completed prior to completing the work');
}
};
function fetchData() {
var token = $('[name=__RequestVerificationToken]').val();
$.ajax({
beforesend: showProgress(),
type: 'GET',
headers: { "__RequestVerificationToken": token },
url: getAppPath() + 'AppSettings/GetAppSettings',
dataType: 'json',
success: function (data) {
// console.log(data);
$scope.items = data;
$scope.$apply();
console.log($scope.items);
},
complete: hideProgress,
error: function (ex) {
ShowErrorPopup('An error has occurred. Please contact System Administrator.');
}
});
};
function validate() {
var val = true;
if ($("input").val().trim() == "") {
val = false;
}
return val;
}
fetchData();
});
})();
Problem:
On save click i am getting null on server side. Where i am going wrong here?

Try adding
contentType: 'application/json; charset=utf-8',
See this answer

Your code wrong here:
data: { AppSetting: $scope.items }
It should be
data: $scope.items
In your saveClick function: $scope.items now is []. It should have some values as you expect. Depend on your case it is from client or a default value for testing:
$scope.items = [{lng_AppSettings: 1, str_SettingName : 'Name 1'},
{lng_AppSettings: 2, str_SettingName : 'Name 2'}];

Related

I am sending post method to server but receiving get method

I am working on .net core 3.1 api
I got error when calling api. Server responce 405
jquery.min.js:2 GET https://localhost:44345/api/Home/AddUpdateUser?callback=jQuery351026836393378483203_1613635815143&name=Ahsan&email=ahsan%40gmail.com&password=asdsdasda&_=1613635815145 net::ERR_ABORTED 405
This is my api controller class
public class HomeController : ControllerBase
{
private IRegisterUser _user;
private IMapper _mapper;
public HomeController(IRegisterUser user, IMapper mapper)
{
_user = user;
_mapper = mapper;
}
//api/Home
[HttpGet]
public IActionResult GetAllUser()
{
var users = _user.GetAllUser();
if (users != null)
{
var userVm = _mapper.Map<List<RegisterUserVm>>(users);
return Ok(userVm);
}
return Ok("Some error occured");
}
//api/Home
[HttpPost]
[Route("[action]")]
[Route("api/Home/AddUpdateUser")]
public IActionResult AddUpdateUser([FromBody] RegisterUserVm userVm)
{
//userVm.MacAddress = GetMacAddress();
var user = _mapper.Map<User>(userVm);
var msg = _user.AddUser(user);
string[] message = { "200", "testing" };
return Ok(message);
}
//api/Home/{id}
[HttpDelete]
public IActionResult DeleteUser(Guid Id)
{
var msg = _user.DeleteUser(Id);
return Ok(msg);
}
[HttpGet]
[Route("[action]")]
[Route("api/Home/GetUserById")]
public IActionResult GetUserById(Guid Id)
{
var user = _user.GetUserById(Id);
var userVm = _mapper.Map<RegisterUserVm>(user);
if (userVm != null)
return Ok(userVm);
return Ok("Some error occured");
}
}
Here is my ajax call
<script>
$("#button").click(function (e) {
e.preventDefault()
var data = {
name: "Ahsan",
email: "ahsan#gmail.com",
password: "asdsdasda"
};
jQuery.support.cors = true;
$.ajax({
type: "POST",
dataType: 'jsonp',
url: "https://localhost:44345/api/Home/AddUpdateUser",
data: data,
contentType: "application/json; charset=utf-8",
success: function (result) {
debugger;
alert('ok');
},
error: function (result) {
debugger;
alert('error');
}
});
});
</script>
Change your ajax to this:
$.ajax({
url: "https://localhost:44345/api/Home/AddUpdateUser",
data: data,
success: function (result) {
debugger;
alert('ok');
},
error: function (result) {
debugger;
alert('error');
}
});
and remove [post] from your action header and fix the route:
[Route("~/api/Home/AddUpdateUser")]
public IActionResult AddUpdateUser([FromBody] RegisterUserVm userVm)
{
....
}
And you will have to resolve CORS issue by adding to startup this code:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("AllowAnyOrigins", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
services.AddControllers()
.AddNewtonsoftJson(options =>
options.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver());
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseCors("AllowAnyOrigins");
//app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
````

Pass javascript array to c# array/list using $.post without specifing datatype as json

I have a model created in javascript as follows
function Vehicle() {
this.type = 'Vehicle';
this.data = {
VehicleKey: null
}
};
I have a similar model created in c# as follows
public class Vehicle
{
public string VehicleKey { get; set; }
}
Now I am building an array of VehicleKeys in javascript as follows
function GetVehicleDetails(inputarray) {
var vehicleKeys = [];
for (var i = 0; i < inputarray.length; i++) {
var vehicleObject = new Vehicle();
vehicleObject.data.VehicleKey = inputarray[i].VehicleKey ? inputarray[i].VehicleKey : null;
vehicleKey.push(vehicleObject.data);
}
return vehicleKeys ;
}
I am calling the $.post(url, data) as follows
var objectToSend = GetVehicleDetails(selectedVehicles);
var data = JSON.stringify({
'vehicles': objectToSend
});
$.post(url, data)
.done(function (result) {
if (result) {
download(result, 'VehicleReport.xlsx', { type: 'application/octet-stream' });
console.log("Report created successfully");
}
else {
console.log("Error creating report");
}
}).fail(function (error) {
console.log("Error creating report.");
});
The MVC Controller has a method to accept Vehicles with multiple VehicleKeys coming from javascript
public byte[] CreateVehicleReport(List<Vehicle> vehicles)
{
//Generation of report and pass it back to javascript
}
Here I am able to submit the data in javascript as 10 and 11 for Vehicles but when it catches the c#, the count is coming as 0.
Any help would be greatly appreciated.
$.post is not posted Content-Type json data so you need to use $.ajax
function GetVehicleDetails(inputarray) {
var vehicleKeys = [];
for (var i = 0; i < inputarray.length; i++) {
var vehicleObject = {}; // Set Object
vehicleObject.VehicleKey = inputarray[i].VehicleKey ? inputarray[i].VehicleKey : null;
vehicleKeys.push(vehicleObject);
}
return vehicleKeys;
}
var objectToSend = GetVehicleDetails(selectedVehicles);
$.ajax({ type: 'POST',
url: url,
data: JSON.stringify(objectToSend),
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('data: ' + data);
},
}).done(function () {
if (result) {
console.log("Report created successfully");
}
else {
console.log("Error creating report");
}
}).fail(function () {
console.log("Error creating report.");
});
C# Method
[HttpPost("CreateVehicleReport")]
public byte[] CreateVehicleReport([FromBody]List<Vehicle> vehicles)
{
return null;
//Generation of report and pass it back to javascript
}
I used a similar approach once but with ajax and it went like this:
fill your array directly with the properties inside your class as object { } make sure the names are exactly the same:
function GetVehicleDetails(inputarray) {
var data_Temp = [];
for (var i = 0; i < inputarray.length; i++) {
var _vehiclekey = inputarray[i].VehicleKey ? inputarray[i].VehicleKey : null;
data_Temp.push({ VehicleKey : _vehiclekey });
});
return data_Temp;
}
var objectToSend = GetVehicleDetails(selectedVehicles);
var JsonData = JSON.stringify({ vehicles: objectToSend });
$.ajax({
type: "POST",
contentType: "application/json",
url: "/controllerName/actionName", //in asp.net using mvc ActionResult
datatype: 'json',
data: JsonData,
success: function (response) {
},
error: function (response) {
console.log(response);
}
});
And the ActionResult in the controller should look like this:
[HttpPost]
public ActionResult Create(List<Vehicle> vehicles)
{
//do whatever you want with the class data
}
I don't know if this is helpful for you but this always works for me and i hope it helps.

Why Ajax edit code not work properly? can you help me?

I m working on simple registration i have two forms one is registration another is city, When city is newly added it get added update perfectly but when i use city in registration form eg pune. pune will not get edited or updated, code written in ajax
function UpdateCity(Ids) {
debugger;
var Id = { Id: Ids }
$('#UpdateModel').modal('show');
$.ajax({
type: 'GET',
url: "/City/GetCityDetail",
data: Id,
dataType: "json",
success: function (city) {
$('#EditCityName').val(city.CityName);
$('#EditCityId').val(city.CityId);
}
})
$('#UpdateCityButton').click(function () {
var model = {
CityName: $('#EditCityName').val(),
CityId: $('#EditCityId').val()
}
debugger;
$.ajax({
type: 'POST',
url: "/City/UpdateCity",
data: model,
dataType: "text",
success: function (city) {
$('#UpdateModel').modal('hide');
bootbox.alert("City updated");
window.setTimeout(function () { location.reload() }, 3000)
}
})
})
}
Controller
public bool UpdateCity(City model, long CurrentUserId)
{
try
{
var city = db.Cities.Where(x => x.CityId == model.CityId && x.IsActive == true).FirstOrDefault();
if (city == null) return false;
city.CityName = model.CityName;
city.UpdateBy = CurrentUserId;
city.UpdateOn = DateTime.UtcNow;
db.SaveChanges();
return true;
}
catch (Exception Ex)
{
return false;
}
}
A few stabs in the dark here but, try changing your code to the following (with comments).
Controller:
// !! This is a POST transaction from ajax
[HttpPost]
// !! This should return something to ajax call
public JsonResult UpdateCity(City model, long CurrentUserId)
{
try
{
var city = db.Cities.Where(x => x.CityId == model.CityId && x.IsActive == true).FirstOrDefault();
if (city == null) return false;
city.CityName = model.CityName;
city.UpdateBy = CurrentUserId;
city.UpdateOn = DateTime.UtcNow;
db.SaveChanges();
// !! Change return type to Json
return Json(true);
}
catch (Exception Ex)
{
// !! Change return type to Json
return Json(false);
}
}
Script:
function UpdateCity(Ids) {
//debugger;
var Id = { Id: Ids };
$('#UpdateModel').modal('show');
$.ajax({
type: 'GET',
url: "/City/GetCityDetail",
data: Id,
dataType: "json",
success: function (city) {
$('#EditCityName').val(city.CityName);
$('#EditCityId').val(city.CityId);
},
error: function () {
// !! Change this to something more suitable
alert("Error: /City/GetCityDetail");
}
});
$('#UpdateCityButton').click(function () {
var model = {
CityName: $('#EditCityName').val(),
CityId: $('#EditCityId').val()
};
//debugger;
$.ajax({
type: 'POST',
url: "/City/UpdateCity",
data: model,
// !! Change return type to Json (return type from Server)
dataType: "json",
success: function (city) {
// !! Check result from server
if (city) {
$('#UpdateModel').modal('hide');
bootbox.alert("City updated");
// !! Why reload location?
// window.setTimeout(function () { location.reload(); }, 3000);
} else{
// !! Change this to something more suitable
alert("Server Error: /City/UpdateCity");
}
},
error: function () {
// !! Change this to something more suitable
alert("Error: /City/UpdateCity");
}
});
});
}
This should give you some more clues as to what's going on.

ASP.NET MVC Unknown Action when delete is pressed

I have a problem, when I try to delete something, it gives me the following error message:
"Error: Unknown Action"
This is my controller:
[Authorize(Roles = "Admin, Staff")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int? id)
{
string result = null;
try
{
if (id == null)
{
result = HIQResources.errorMessageUnknownAction;
return new JsonResult { Data = result };
}
StudentViewModel vm = new StudentViewModel();
StudentDetail studentDetail = studentManager.GetStudentDetailById(id.Value);
if (studentDetail == null)
{
result = HIQResources.errorMessageUnknownRecord;
return new JsonResult { Data = result };
}
int deleteResult = studentManager.Delete(id.Value);
if (deleteResult == 1)
{
vm.Alert.SetSuccessMessage(HIQResources.messageOperationSuccess);
TempData["alert"] = vm.Alert;
result = HIQResources.messageOperationSuccess;
return new JsonResult { Data = result };
}
else
{
vm.Alert.SetErrorMessage(HIQResources.errorMessageUnableToExecuteOperation);
TempData["alert"] = vm.Alert;
result = HIQResources.errorMessageUnableToExecuteOperation;
return new JsonResult { Data = result };
}
}
catch (DbUpdateException ex)
{
Log.AddLogRecord(LogManager.LogType.Warning, LogManager.LogPriority.Low, LogManager.LogCategory.Teacher, ex.Message, ex.StackTrace, base.GetLoggedUser());
result = HIQResources.errorMessageUnableToDeleteRecord;
return new JsonResult { Data = result };
}
catch (Exception ex)
{
Log.AddLogRecord(LogManager.LogType.Error, LogManager.LogPriority.High, LogManager.LogCategory.Inscription, ex.Message, ex.StackTrace, base.GetLoggedUser());
result = HIQResources.errorMessageExceptionOccurred;
return new JsonResult { Data = result };
}
}
This is my Javascript:
$('#ModalDeleteButton').on("click", function (e) {
var token = $('input[name="__RequestVerificationToken"]').val();
$.post("/Student/Delete/",
{
__RequestVerificationToken: token,
id: id
},
function (data) {
$('#myModal .close').click();
var baseurl = '#Url.Action("Index")';
var url = baseurl + "?message=" + data;
window.location.href = url;
});
});
I would need more specific details on this error, it seems to me that the controller and the javascript is right, so I don't really know what possibly can be.
If you're going to call $.post then you need to put the [HttpPost] attribute above the method definition. Otherwise, it just assumes that method is actually a GET (which is why the action is "unknown")
EDIT:
Try changing your $.post to this:
$.ajax({
type: "POST",
data: {
__RequestVerificationToken: token,
id: id
},
success: function(data) {
$('#myModal .close').click();
var baseurl = '#Url.Action("Index")';
var url = baseurl + "?message=" + data;
window.location.href = url;
}
});

How to pass Array from jQuery Ajax to the MVC 5 Action?

I try to pass my grid Data from jQuery to the MVC Action via Ajax.
I have a button "Save" on my page, and this is jQuery code for click:
var result = [];
$('#btnSave').click(function () {
$('#tblMatters tbody tr.mattersRow').each(function () {
var item = {};
if ($(this).find('td.qbmatter > div.dropdown').length > 0) {
item.QBMatter = $(this).find('td.qbmatter > div.dropdown > a').text();
} else {
item.QBMatter = $(this).find('td.qbmatter').text();
}
item.Hours = $(this).find('td.hours').text();
item.Person = $(this).find('td.person').text();
if ($(this).find('td.rate > div.dropdown').length > 0) {
item.Rate = $(this).find('td.rate > div.dropdown > a').text();
} else {
item.Rate = $(this).find('td.rate').text();
}
item.Amount = $(this).find('td.amount').text();
result.push(item);
});
$.ajax({
url: "/Home/SaveQBMatter",
type: "POST",
data: { 'Matters': result },
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) { alert("Success!"); },
error: function () { alert("An error has occured!!!"); }
});
});
I checked the result array and it's correct. It contains every value that should be.
In my HomeController I have the following model for my data:
public class QBMatter
{
public string QBDescription { get; set; }
public string Person { get; set; }
public decimal Hours { get; set; }
public int Rate { get; set; }
public decimal Amount { get; set; }
}
And the following Action:
public ActionResult SaveQBMatter (QBMatter[] Matters)
{
DBAccess dba = new DBAccess();
int QBMatterID = 0;
foreach (QBMatter qb in Matters)
{
dba.InsertQBMatter(qb.QBDescription, qb.Person, qb.Hours, qb.Rate, qb.Amount, ref QBMatterID);
}
return RedirectToAction("Home", "Index", "Home");
}
But I always getting the "An error has occured!!!" result... And I even don't get to the action, so error somewhere on the ajax level...
What I'm doing wrong?
You need to stringify the data while sending it.
Try:
$.ajax({
url: "/Home/SaveQBMatter",
type: "POST",
data: JSON.stringify({ 'Matters': result }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Success!");
},
error: function () {
alert("An error has occured!!!");
}
});

Categories

Resources