I have a need to call a method on my controller to return a complex type using the JQuery.Ajax method.
function CallMethodTest(Id) {
//alert(Id);
$.ajax({
type: 'POST',
url: '/MyController/MyMethod',
dataType: "json",
contentType: "application/json; charset=utf-8",
//data: "{'Id': '" + Id + "'}",
success: function (data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
[System.Web.Services.WebMethod]
public string MyMethod()
{
return "ABC"; // Gives me the error on the first alert of "200" and the second alert "Syntax Error: Invalid Character"
return "1"; // Works fine
}
As the code explains, if I return an integer (as a string) the return works and I alert "1", however, If I try and return any alpha characters I get the alerts shown in the comments of MyMethod.
From your code, it looks as though you are returning the value from your Controller url: "/MyController/MyMethod"
If you are returning the value from your controller, then get rid of the [System.Web.Services.WebMethod] code and replace it with this ActionResult
[HttpPost]
public ActionResult MyMethod(){
return Json("ABC");
}
Also, if you are ever going to call a method in your controller via GET then use
public ActionResult MyMethod(){
return Json("ABC", JsonRequestBehavior.AllowGet);
}
In View You use the following code,
function ItemCapacity() {
$.ajax({
type: "POST",
url: '#Url.Action("ItemCapacityList", "SalesDept")',
data: { 'itemCategoryId': itemCategoryIds },
dataType: 'json',
cache: false,
success: function (data) {
var capacityCounter = 0;
var capacitySelected = "";
for (var i = 0; i < rowsCount; i++) {
var tr = $("#gvSpareSetItemsDetails tbody tr:eq(" + i + ")");
var categoryId = $(tr).find('td:eq(5)').text();
var isSelectOrNot = $(tr).find('td:eq(1)').find('select');
if (isSelectOrNot.is('select')) {
$.map(data, function (item) {
if (categoryId == item.ItemCategoryID) {
isSelectOrNot.get(0).options[isSelectOrNot.get(0).options.length] = new Option(item.CapacityDescription, item.ItemCapacityID);
capacityCounter = capacityCounter + 1;
capacitySelected = item.ItemCapacityID;
}
});
if (capacityCounter == 1) {
isSelectOrNot.val(capacitySelected);
}
capacityCounter = 0;
capacitySelected = "";
}
}
},
error: function () { alert("Connection Failed. Please Try Again"); }
});
}
}
In the Controller Use the following Code,
public JsonResult ItemCapacityList(string itemCategoryId)
{
List<ItemCapacity> lsItemCapacity = new List<ItemCapacity>();
string[] itemCategory = itemCategoryId.Split('#');
int itemCategoryLength = itemCategory.Length, rowCount = 0;
string itemCategoryIds = string.Empty;
for (rowCount = 0; rowCount < itemCategoryLength; rowCount++)
{
itemCategoryIds += "'" + itemCategory[rowCount].Trim() + "',";
}
itemCategoryIds = itemCategoryIds.Remove(itemCategoryIds.Length - 1);
lsItemCapacity = salesDal.ReadItemCapacityByCategoryId(itemCategoryIds);
return new JsonResult { Data = lsItemCapacity };
}
Related
Here is my controller. I am trying to pass the value through an if statement but it's not equalling (==) the string of "2019".
[HttpPost]
public ActionResult Extract(string[] response)
{
string statementQuery = "";
if (response!=null)
{
for (var i = 0; i < response.Length; i++)
{
if (response[i] == "2019")
{
statementQuery = "select statementPath from ClientStatements_Inventory where statementYear = '" + response[i] + "';";
}
}
}
Here is my ajax call. Is it something to do with the way it is sending to my controller? or my if statement?
$('#main-content-submit').click(function () {
var labelArray = [];
labelArray = $("input:checkbox:checked").map(function () {
return $(this).closest('label').text();
}).get();
console.log(labelArray);
event.preventDefault();
$.ajax({
type: 'POST',
url: '/Home/Extract',
data: JSON.stringify({ response:labelArray }),
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert("Month and ear passed to controller");
},
error: function (err, result) {
alert("Error in Extract" + err.responseText);
},
});
return false;
});
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 try to save a file (image) on C# MVC and JS with the following function js
function Add() {
var data = new FormData();
var files = $("#txtUploadFile").get(0).files;
var cod = document.getElementById('cod').value;
var mat = document.getElementById('mat').value;
var status = document.getElementById('status').value;
var plant = document.getElementById('plant').value;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++) {
data.append("file" + x, files[x]);
data.append("mat", mat);
data.append("status", status);
data.append("plant", plant);
data.append("code", cod);
}
$.ajax({
type: 'POST',
url: '/Pred/Admin/AddPred',
contentType: false,
processData: false,
data: data,
success: function (response) {
if(response.msg == 1)
{
refreshTable(response.data);
}
alert('Predio agregado.');
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
}
});
}
}
}
and on the codebehind I used it
public ActionResult AddPred()
{
int isInsert=0;
string route = ConfigurationManager.AppSettings["MAPS_ROUTE"];
string[] status, plants, mats, codes;
int stat;
try
{
var requeststatus = Request.Params;
status = requeststatus.GetValues("status");
plants = requeststatus.GetValues("plant");
codes = requeststatus.GetValues("cod");
mats = requeststatus.GetValues("mat");
if (status[0] == "On")
stat= 1;
else
stat= 0;
string plant = plants[0];
string mat = mats[0];
string code = codes[0];
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent != null && fileContent.ContentLength > 0)
{
var fileName = fileContent.FileName;
var path = Path.Combine(Server.MapPath(route), fileName);
path = Server.MapPath(route) + fileName;
var sqlpath = "." + route + "/" + fileName;
fileContent.SaveAs(path);
isInsert = ma.InsertPred(code, mat, stat, plant, sqlpath);
}
}
merge.preds = ma.GetPreds();
return Json(new { success = true, data = merge.preds, msg = isInsert }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("add failed");
}
}
But the server response ever is
POST myserver/Preds/Admin/AddPred 500 (Internal Server Error)
and I used console.log but I can't to get the error information, When used this code on local side, it's runs Okey, save the image and return model for refresh the front, but when put the aplication on the server, only return error, others funtions works (modal show, return model with json) but doesn't work save a image, I set permissions (write, load, modify) on the server folder,
someone give a idea for solves this problem, I don't know whats wrong
Try like this :
function getCities(id) {
$.ajax({
type: "POST",
url: "#Url.Action("Index", "Default")",
data: '{id: id }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//alert(response.responseData);
window.location = '/Default/YourView';//
},
error: function (response) {
alert("error!"); //
}
});
}
//In your controller
public JsonResult Index(string id)
{
merge.country= mp.Country();
merge.city= mp.City(id);
return Json("you can return an object or a string, what you want");
}
Error provide that input string was not in correct format in this line:
objproject.CategoryStatus(Convert.ToInt32(Id), true);
This is my aspx code:
[WebMethod]
public static void ActivateSelected(String Id)
{
clsCategoryBL objproject = new clsCategoryBL();
string[] arr = Id.Split(',');
foreach (var id in arr)
{
if (!string.IsNullOrEmpty(id))
{
objproject.CategoryStatus(Convert.ToInt32(Id), true);
}
}
}
This is my jQuery bind code:
function ActivateSelected()
{
var ids = '';
var cells = Array.prototype.slice.call(document.getElementById("example1").getElementsByTagName('td'));
debugger;
for (var i in cells) {
var inputArray = cells[i].getElementsByTagName('input');
for (var i = 0; i < inputArray.length; i++) {
if (inputArray[i].type == 'checkbox' && inputArray[i].checked == true) {
debugger;
ids += inputArray[i].id + ',';
}
}
}
debugger;
var urldata = "WebForm5.aspx/ActivateSelected";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
cache: "false",
url: urldata,
data: "{Id:'" + ids + "'}",
success: function (dt)
{
debugger;
debugger;
$("#example1").DataTable();
//$("#example1").bind;
debugger;
},
error: function (result) {
alert("Error");
//console.log();
//alert(result);
}
});
}
This is my BL Class:
public string CategoryStatus(int CategoryID, bool Status)
{
using (KSoftEntities db = new KSoftEntities())
{
try
{
var ProjectDetails = db.tblCategories.Where(i => i.CategoryID == CategoryID).ToList();
ProjectDetails[0].Status = Status;
db.SaveChanges();
if (Status == true)
return "Record Activated successfully";
else
return "Record deactivated successfully";
}
catch (Exception ex)
{
}
return "Error on updation";
}
}
The Last ID is attached with extra comma,
Like : "1234,123,12345,"
spliting string of above example will create array of 4 elements, having empty string in last element. Thats why its Throwing error.
You need to handle the ids += inputArray[i].id + ','; in jquery.
here you can check whether the id is last id in the list and does that require comma after that.
function ActivateSelected()
{
var ids = '';
var cells = Array.prototype.slice.call(document.getElementById("example1").getElementsByTagName('td'));
debugger;
for (var i in cells) {
var inputArray = cells[i].getElementsByTagName('input');
for (var i = 0; i < inputArray.length; i++) {
if (inputArray[i].type == 'checkbox' && inputArray[i].checked == true) {
debugger;
ids += inputArray[i].id + ',';
}
}
}
ids = ids.substring(0,ids.lastIndexOf(','));
debugger;
var urldata = "WebForm5.aspx/ActivateSelected";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
cache: "false",
url: urldata,
data: "{Id:'" + ids + "'}",
success: function (dt)
{
debugger;
debugger;
$("#example1").DataTable();
//$("#example1").bind;
debugger;
},
error: function (result) {
alert("Error");
//console.log();
//alert(result);
}
});
}
I have an observable array Object that which is generated like this:
self.SelectedVariable = ko.observableArray();
self.VarUpdate = function (data) {
$.getJSON("/api/Variable/" + ko.toJS(data.VarID), ko.toJS(data.VarID), function (Result) {
for (var i = 0; i < Result.length; i++) {
element = Result[i];
self.SelectedVariable({ VariableID: ko.observable(element.VariableID), VariableDateLastUpdated: ko.observable(element.VariableDateLastUpdated), VariableName: ko.observable(element.VariableName), VariableDescription: ko.observable(element.VariableDescription), VariableValue: ko.observable(element.VariableValue), VariableType: ko.observable(element.VariableType) });
};
});
When I try to pass the SelectedVariable object to my WebAPI method using this AJAX call
$.ajax({
url: "/api/Variable?Del=0",
data: { vardata: ko.toJS(self.SelectedVariable) },
type: "PUT",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
, all the related object shows null on all the fields.
I have tried almost every combination to get the SelectedVariable Object to parse correctly to my WebAPI method:
data: { vardata: ko.toJS(self.SelectedVariable) },
data: { vardata: ko.toJSON(self.SelectedVariable) },
data: { vardata: JSON.Stringify(self.SelectedVariable) },
data: { vardata: self.SelectedVariable },
and have tried to manually decrypt JSON object on WebAPI side using:
public void Put([FromUri] int Del, [FromBody]string vardata)
{
Variables vari = JsonConvert.DeserializeObject<Variables>(vardata);
var Item = (from c in TMIRE.Variables
where c.VariableID == vari.VariableID
select c).First();
if (Del == 0)
{
Item.VariableDateUpdated = DateTime.Now;
Item.VariableName = vari.VariableName;
Item.VariableDescription = vari.VariableDescription;
Item.VariableValue = vari.VariableValue;
Item.VariableType = vari.VariableType;
And It is still null value.
Any Advice would be greatly appreciated!
UPDATE
Changed my WebAPI method to reflect as follows:
public void Put([FromUri] int Del, IEnumerable<Variables> vardata)
{
var Item = (from c in TMIRE.Variables
where c.VariableID == vardata.Select(x => x.VariableID).First()
select c).First();
if (Del == 0)
{
Item.VariableDateUpdated = DateTime.Now;
vardata.Select(a => Item.VariableName = a.VariableName);
vardata.Select(b => Item.VariableDescription = b.VariableDescription);
vardata.Select(c => Item.VariableValue = c.VariableValue);
vardata.Select(d => Item.VariableType = d.VariableType);
}
and now the vardata object gets the value but all objects within are null
My Ajax method looks like this:
alert(ko.toJSON(self.SelectedVariable));
$.ajax({
url: "/api/Variable?Del=0",
contenttype: "application/x-www-form-urlencoded",
data: "=" + ko.toJSON(self.SelectedVariable()),
type: "PUT",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
The alert gives me this response
The Variables Class
public class Variables
{
public int VariableID { get; set; }
public DateTime VarialbeDateLastUpdated { get; set; }
public string VariableName { get; set; }
public string VariableDescription { get; set; }
public string VariableValue { get; set; }
public string VariableType { get; set; }
}
Working Code
By using this Ajax call
$.ajax({
url: "/api/Variable?Del=0",
contenttype: "application/x-www-form-urlencoded",
data: "=" + ko.toJSON(self.SelectedVariable),
type: "PUT",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
and then using Newtonsoft to deserialize the object on WebAPI using this method:
public void Put([FromUri] int Del, [FromBody]string vardata)
{
Variables vari = JsonConvert.DeserializeObject<Variables>(vardata.Substring(1, vardata.Length-2));
var Item = (from c in TMIRE.Variables
where c.VariableID == vari.VariableID
select c).First();
if (Del == 0)
{
Item.VariableDateUpdated = DateTime.Now;
Item.VariableName = vari.VariableName;
Item.VariableDescription = vari.VariableDescription;
Item.VariableValue = vari.VariableValue;
Item.VariableType = vari.VariableType;
}
else
{
Item.VariableDateUpdated = DateTime.Now;
Item.VariableActive = false;
}
TMIRE.SaveChanges();
}
I Got it to work
Try this...
public void Put([FromUri] int Del, IEnumerable<Variables> vardate){}
Since you're building a collection on the client self.SelectedVariable = ko.observableArray();, you will need the API to receive an IEnumerable.
In the Ajax call, I think it would be best to use:
data: { vardata: ko.toJSON(self.SelectedVariable) }
as this will give you a JSON representation of the collection.
Also, on the KO side, shouldn't you be pushing elements into the collection? self.SelectedVariable.push({...}); or you will end up with only the final result.
Change assignment to this:
self.SelectedVariable = ko.observableArray();
self.VarUpdate = function (data) {
$.getJSON("/api/Variable/" + ko.toJS(data.VarID), ko.toJS(data.VarID), function (Result) {
var selection = self.SelectedVariable;
for (var i = 0; i < Result.length; i++) {
var element = Result[i];
selection.push(element);
};
});
Then, Change the ajax method to convert to json:
$.ajax({
url: "/api/Variable?Del=0",
content-type: "application/x-www-form-urlencoded",
data: "=" + JSON.stringify(ko.toJSON(self.SelectedVariable)),
type: "PUT",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
Also try removing [FromBody].
public void Put([FromUri] int Del, IEnumerable<Variables> vardata)
{
...
}
It looks like making the serialized objects in vardata as ko.observable objects is confusing mvc serialization for the parameters.
different data assignments to attempt:
data: "=" + JSON.stringify(ko.toJSON(self.SelectedVariable))
data: "=" + JSON.stringify(self.SelectedVariable())
data: "=" + self.SelectedVariable()
data: "=" + $.parseJSON(ko.toJSON(self.SelectedVariable))
What you're passing self.SelectedVariable isn't an array. Should you not be calling it just an observable? Otherwise, you need to be adding your results with self.SelectedVariable.push(resultObject).
By using this Ajax call
$.ajax({
url: "/api/Variable?Del=0",
contenttype: "application/x-www-form-urlencoded",
data: "=" + ko.toJSON(self.SelectedVariable),
type: "PUT",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
and then using Newtonsoft to deserialize the object on WebAPI using this method:
public void Put([FromUri] int Del, [FromBody]string vardata)
{
Variables vari = JsonConvert.DeserializeObject<Variables>(vardata.Substring(1, vardata.Length-2));
var Item = (from c in TMIRE.Variables
where c.VariableID == vari.VariableID
select c).First();
if (Del == 0)
{
Item.VariableDateUpdated = DateTime.Now;
Item.VariableName = vari.VariableName;
Item.VariableDescription = vari.VariableDescription;
Item.VariableValue = vari.VariableValue;
Item.VariableType = vari.VariableType;
}
else
{
Item.VariableDateUpdated = DateTime.Now;
Item.VariableActive = false;
}
TMIRE.SaveChanges();
}