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]
Related
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", "")]
I'm trying to take input from Users through a checkbox and store it in a table in my SQL DB, I've created all the link properly and my post AJAX call works well because I was able to receive information in my DB. The problem is the parameter received in my controller is receiving a null value which is storing a null value in my table, I know that my checkbox is pulling the right information because im printing it before hand but I feel like my AJAX setup may not be stringifying it properly.
$("#submitButton").click(function() {
var results = {};
$questions = $('#optionData');
for (i = 1; i < 6; i++) {
if ($questions.find('#option' + i).prop('checked')) {
results['option' + i] = $questions.find('#option' + i).val();
}
newResult = JSON.stringify(results)
};
console.log(newResult);
$.ajax({
url: "/Home/SaveData",
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: (newResult),
success: function(data) {
if (data == null) {
alert("Something went wrong");
}
},
failure: function(data) {
alert(data.dataText);
},
error: function(data) {
alert(data.dataText);
}
});
});
[HttpPost]
public ActionResult SaveData(string Options)
{
dataInsertion dataInsertion = new dataInsertion
{
// questionID = object.QuestionId,
options = Options,
// },
// companyID = object.companyID
};
try
{
if (ModelState.IsValid)
{
DB.dataInsertions.Add(dataInsertion);
DB.SaveChanges();
// RedirectToAction("Home");
}
}
catch (Exception e)
{
Console.WriteLine("error" + e);
}
return Json(new { sucess = "true" });
}
I have a JQuery function that load some data from C# and update information on my view.
I must to load a large dataset and all works fine, but for some reason i must to load a dynamic list and elaborate its from JQuery.
The list is "listCasistiche" and when i load it from MVC the JQuery function goes in error.
How can i take this list?
The JQuery function is this:
var data = $('#jqxgrid').jqxGrid('getrowdata', rowindex);
var uf = new FormData();
uf.append("id", data.Id);
var url = "/Clienti/LoadSelezionato";
$.ajax({
type: "POST",
url: url,
dataType: 'json',
contentType: false,
processData: false,
data: uf,
error: function () {
// The function go in error
},
success: function (result) {
if (result != "error") {
result.listCasistiche.forEach(function (entry) {
alert(entry.IdCasistica);
});
ricaricaNeri();
$('#OwnLead').val(result.ownerLead);
$('#dataLead').datepicker('setDate', result.dataLead);
}
}
});
The MVC LoadSelezionato function is this. All other parameters are loaded well:
[HttpPost]
public ActionResult LoadSelezionato(FormCollection form)
{
int id = Convert.ToInt32(form["id"]);
try
{
Cliente clienteLead = conc.Clientes.FirstOrDefault(x => x.Id == id);
if (clienteLead != null)
{
var elemento = new
{
ownerLead = clienteLead.OwnerLead,
dataLead = clienteLead.DataLead,
listCasistiche = conc.CasisticheClientes.Where(x => x.IdCliente == id).ToList()
};
return Json(elemento, JsonRequestBehavior.AllowGet);
}
else
{
return Json("error", JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
return Json("error", JsonRequestBehavior.AllowGet);
}
}
Thanks to all
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);
});
I have a WebMethod being called from ajax, trying to iterate through the returned data. The data being returned is "{ BusinessTypeID = 2 }". I'm trying to figure out how to just get the value 2?
//Function called from ajax
[System.Web.Services.WebMethod]
public static string[] GetTerminalBusinessTypes(string terminalID)
{
DataClassesDataContext db = new DataClassesDataContext();
List<string> results = new List<string>();
try
{
var terminalBusinessTypes = (from bt in db.BusinessTypes
join obt in db.OxygenateBlenderBusinessTypes on bt.BusinessTypeID equals obt.BusinessTypeID
where obt.OxygenateBlenderID == Convert.ToInt32(terminalID)
select new
{
bt.BusinessTypeID
}).ToList();
for (int i = 0; i < terminalBusinessTypes.Count(); i++)
{
results.Add(terminalBusinessTypes[i].ToString());
}
}
catch (Exception ex)
{
}
return results.ToArray();
}
The ajax function:
function PopulateTerminalBusinessTypes(terminalID) {
$.ajax({
type: "POST",
url: "OxygenateBlenderCertificationApplication.aspx/GetTerminalBusinessTypes",
data: "{'terminalID':" + terminalID + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var targetValue = data.d;
var items = $('#cblTerminalBusinessType input:checkbox');
$.each(targetValue, function (key, targetValue) {
alert(data[index].BusinessTypeID);
});
}
})//end ajax
}
When your web service returns the json value, asp.net wraps in an object, with the key being d and the value being your json string. Review this link for more info.
You have to parse the value string into a json object. Using jQuery (v1.4.1 or higher):
jQuery.parseJSON(targetValue);
To be honest I cannot see where your "index" is defined.
Shouldn't the alert line read
$each(targetVale, function(key, item) {
// on second look, this wont work as you are converting toString()
alert(targetValue[key].BusinessTypeId)
// this should
alert(item)
});
You could also throw a debugger; line above the alert and see the values being traversed.
You may want to try returning a JSON string from C#:
public static **string** GetTerminalBusinessTypes(string terminalID)
...
var oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(results);
return sJSON;