i'm trying pass a object to a controller, but in debug when i check data, the object arrive null. I already try to many things, but never get success.
Ajax:
function filtro() {
var nome = document.getElementById("nome").value;
var idade = document.getElementById("idade").value;
var dataCriacao = document.getElementById("data-criacao").value;
var dataInicio = document.getElementById("data-inicio").value;
var dataFim = document.getElementById("data-fim").value;
var tipo = document.getElementById("tipo").value;
var ativo = document.getElementById("ativo").checked;
var filtro = {
IdadeText: idade,
Nome: nome,
DataDestaqueInicio: dataInicio,
DataDestaqueFim: dataFim,
DataAnuncioCriacao: dataCriacao,
Ativo: ativo,
Tipo: tipo,
};
debugger
$.ajax({
type: "POST",
url: '#Url.Action("Anuncios", "Admin")',
data: filtro,
contentType: 'application/json;',
success: function (result) {
}
})
}
My controller:
[HttpPost]
public async Task<JsonResult> Anuncios(FiltroAnuncioDTO filtro,int pg = 1)
{
return Json("ok");
}
the result:
Solved removing [ClaimsAuthorize("Admin", "")]
Related
I made the user input part of my project as a modal (pop-up), so I need to transfer the data to the back side (controller) without refreshing the page. For this reason, I chose to use ajax, but I have a problem.
Here my Register Controller.
[HttpPost]
public JsonResult Register(RegisterViewModel formData)
{
var user = new UserRegisterDto
{
FirstName = formData.FirstName,
LastName = formData.LastName,
Email = formData.Email,
Password = formData.Password,
PhoneNumber = formData.PhoneNumber,
UserType = Data.Enums.UserTypeEnum.user
};
var response = _userService.AddUser(user);
return new JsonResult("Data is Saved");
}
Here my ajax code
$('#btnRegister').click(function() { debugger
var user = {
FirstName: $('#inputUserFirstName').val(),
LastName: $('#inputUserLastName').val(),
Email: $('#inputUserEmail').val(),
Password: $('#inputUserPassword').val(),
PasswordConfirm: $('#inputUserPasswordConfirm').val(),
PhoneNumber: $('#inputUserPhoneNumber').val()
};
$.ajax({
type: 'Post',
url: '/Auth/Register',
data: JSON.stringify(user),
contentType:'application/json; charset=utf-8;',
dataType: 'json',
success: function() {
alert("saved");
},
error: function() {
alert("no saved");
}
});
When I debugged, I saw that the formData parameter in the controller was not getting any data.
I couldn't find where I made the mistake.
You will need to JSON.stringify() your data to transfer it in the request.
Your request should look like this:
$.ajax({
type: 'Post',
url: '/Auth/Register',
data: JSON.stringify(user),
contentType:'application/json; charset=utf-8;',
dataType: 'json',
success: function() {
alert("saved");
},
error: function() {
alert("no saved");
}
});
For the controller i would do it likes this:
[Route("Auth/Register")]
[HttpPost]
public IActionResult Register([FromBody] RegisterViewModel formData)
{
var user = new UserRegisterDto
{
FirstName = formData.FirstName,
LastName = formData.LastName,
Email = formData.Email,
Password = formData.Password,
PhoneNumber = formData.PhoneNumber,
UserType = Data.Enums.UserTypeEnum.user
};
var response = _userService.AddUser(user);
return Json(new { #Success = true});
}
my project is an MVC Web application I am using ajax call to get a huge list of data as JSON.
Here is the code( i am not sure what I a missing ):
$.ajax({
url: url, //server
type: "POST",
async: true,
data: { id: id },
dataType: "json",
success: function (data) {
debugger;
jQuery.each(data, function (i, val) {
//Success code
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
window.baseShowModalOkCancel("<p>Backlog Data</p>", "<p>Error in Database</p>", "ERROR");
}
});
}
Action Controller:( This is a post method in return statement I can see the list of object with the data.
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetBacklogWithData(string id)
{
using (var db = new LiensTrackerEntities())
{
List<BackLogDataList> backLogData = new List<BackLogDataList>();
List<BackLogData> backLog;
backLog = db.BackLogDatas.OrderBy(x =>x.CaseNumber).ToList();
foreach (var item in backLog)
{
BackLogDataList backLogDataList = new BackLogDataList
{
FileNo = item.FileNo,
BackLogId = item.BackLogID,
FirstName = item.FirstName,
LastName = item.LastName,
Middle = item.Middle,
Suffix = item.Suffix,
Address = item.Address,
Address2 = item.Address2,
City = item.City,
St = item.ST,
Zip = item.SP1ZIP,
AmaesRecordCreatedDate = item.AMAESRecordCreatedDate != null ? item.AMAESRecordCreatedDate.ToString().Split(' ')[0] : null,
AddedInRecipient = item.AddedInRecipient
};
backLogData.Add(backLogDataList);
}
}
return Json(backLogData, JsonRequestBehavior.AllowGet);
}
}
It returns with 200 ok but execute the error function when i look into console i found the following error:
Thee error is due to max json string length. the solution is
MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer
View
function editEmployee(val) {
var a = ko.toJSON(val);
// alert("Hi");
$.ajax({
url: "#Url.Action("editEmployee", "Registration")",
contentType: "application/json; charset=utf-8",
type: "POST", dataType: "json",
data:a,
success: function (data) {
// alert("awa");
debugger;
DisplayUI.getEmpArray(data);
var abc = DisplayUI.getEmpArray();
}
});
}
Controller
[HttpPost]
public JsonResult editEmployee(string ID)
{
//JavaScriptSerializer serializer = new JavaScriptSerializer();
//dynamic item = serializer.Deserialize<object>(ID);
var employee = from s in db.Employee
select s;
try
{
if (!String.IsNullOrEmpty(ID))
{
employee = employee.Where(s => s.empId.Contains(ID));
}
}
catch (Exception ex)
{
}
var val = Json(employee.Select(s => new { s.empId, s.firstName, s.lastName, s.mobilePhn, s.email, s.desigId }).ToList());
return val;
}
Through ajax call I'm passing the value into controller as a string variable(ID). But that value is not passing it is visible as null value. I want to know get the value as a parameter what i should do.
Check whether you are getting json object
var a = ko.toJSON(val); // here you should check whether you are getting json object
Only if you get json object,the value will be bind to the controller.
put alert like this
var a = ko.toJSON(val);
alert(a);
if it is json object it will show like this
[object],[object]
when I call one webapi from ajax, if I return something different from simple string or int, the request is still pending.
here my javascript:
var endPoint = "/api/services/attivita/set";
$.ajax({
url: endPoint,
data: JSON.stringify(
{
'id': attivita.IDTipoAttivita,
'descrizione': $('#Descrizione').val()
}
),
dataType: 'json',
contentType: "application/json;charset=utf-8",
processData: false,
type: 'post',
success: function (data) {
console.log('ok');
},
error: function (data) {
console.log('ko');
}
});
and here webapi code
[System.Web.Http.HttpGet]
[System.Web.Http.HttpPost]
[System.Web.Http.Route("api/services/attivita/set")]
public TipoAttivita SetAttivita([FromBody] dynamic obj)
{
var id = (int)obj.id;
var descrizione = obj.descrizione.ToString();
var nuovo = id == -1;
var attivita = new TipoAttivita()
//do stuff of attivita object
this.CurrentDb.TipoAttivita.Add(attivita);
this.CurrentDb.SaveChanges();
return (attivita);
}
If I change to "public int...." and "return(1);" at the end of the function everything works fine.
in WebApiConfig.cs I have this
var jsonFormatter = new JsonMediaTypeFormatter
{
SerializerSettings = {ReferenceLoopHandling = ReferenceLoopHandling.Ignore}
};
jsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
config.Formatters.Clear();
config.Formatters.Add(jsonFormatter);
Any idea?
Thanks a lot
Try to change return type to IHttpActionResult and return Ok(attivita)
I have a Patient like this in AngularJS
var Patient = {
PatientID : $scope.PatientID,
FirstName: $scope.FirstName,
LastName: $scope.LastName,
Disease: $scope.Disease,
PhoneNo: $scope.PhoneNo
};
Angular Controller
var pData = new FormData();
pData.append("model", Patient);
var getData = angularService.AddPatient(pData);
Angular Service
this.AddPatient = function (patientData) {
var response = $http({
withCredentials: true,
headers: { 'Content-Type': undefined },
transformRequest: angular.identity,
method: "post",
url: "/Student/AddPatient",
data: patientData,
dataType: "json"
});
return response;
}
And my Method in MVC Controller
public String AddPatient() {
var model = Request.Form["model"];
// this giving me an object instead of JSON String
}
Please help me, how do i receive that Patient data, Read and save it in the database, and i dont want to use any loop, i mean like this
// I dont want to do this
var patientData = new FormData();
angular.forEach(Patient, function (value, key) {
patientData.append(key, value);
});