How to send multiple array with jQuery in MVC.NET? - javascript

I have 2 arrays in my Razor view. The first one checked checkboxes and the second is for unchecked. I can send one of them but I don't know how to send both of them. This is my jQuery code:
$(document).ready(function() {
$("#checkAll").click(function() {
$(".checkBox").prop('checked', $(this).prop('checked'));
});
$("#confrim").click(function() {
var selectedIDs = new Array();
var unseletedeIDs = new Array();
$('input:checkbox.checkBox').each(function() {
if ($(this).prop('checked')) {
selectedIDs.push($(this).val());
} else {
unseletedeIDs.push($(this).val());
}
});
var options = {};
options.url = "/Parts/ConfrimAll";
options.type = "POST";
options.data = JSON.stringify(selectedIDs);
options.contentType = "application/json";
options.dataType = "json";
options.success = function(msg) {
alert(msg);
};
options.error = function() {
alert("Error!");
};
$.ajax(options);
});
});
This is the action:
public ActionResult ConfrimAll(int?[] selectedIDs, int?[] unSelectedIDs)
{
if (selectedIDs!=null)
{
foreach (int id in selectedIDs)
{
Part obj = db.Parts.Find(id);
obj.IsOk = true;
db.Entry(obj).State = EntityState.Modified;
}
}
if (unSelectedIDs!=null)
{
foreach (int id in unSelectedIDs)
{
Part objs = db.Parts.Find(id);
db.Parts.Remove(objs);
}
}
db.SaveChanges();
return Json("yes");
}

Have you tried this?
JSON.stringify({ selectedIDs: selectedIDs, unseletedeIDs: unseletedeIDs });
You should have the two parameters selectedIDs and unseletedeIDs in the Action filled with this.

You can provide both array as part of an object to the data parameter of the $.ajax call. Try this:
$("#confrim").click(function() {
var data = {
SelectedIDs: [],
UnSelectedIDs: [],
}
$('input:checkbox.checkBox').each(function() {
data[this.checked ? 'SelectedIDs' : 'UnSelectedIDs'].push(this.value);
});
$.ajax({
url: '/Parts/ConfrimAll',
type: 'POST',
data: data,
success: function(msg) {
console.log(msg);
},
error: function(x, s, e) {
console.log('Error!');
console.log(x, s, e);
}
});
});
Note that it's much better practice to provide an object to the data parameter as jQuery will then encode it for you to the required format, escaping any special characters as it does it.

Related

mvc asp can't update using query from my view

I am trying to have save changes on my script and I just need an update from my table. So far if I clicked the button, the alert success will not pop and can't see any error either. I also tried to verify to my table if the changes is made but the result is nothing happened
Here is the call function from my save button:
<script>
var op = '';
var op_dif = '';
$('#btnSave').click(function () {
op = $('#op').val();
op_dif = $('#op_difficulty').val();
alert(op + " " + op_dif); // I can see the value here
$.post("/Home/UpdateOP", {
'data': JSON.stringify([{
'op': op,
'opDiff': Op_dif
}])
}, function (data) {
var resp = JSON.parse(data);
if (resp["status"] == "SUCCESS") {
alert('Data has been successfully updated');
location.reload();
}
else {
alert('Error!!');
}
});
});
</script>
My view where my update query is located:
public string UpdateOpsDiff(operation[] ops)
{
string res = "";
foreach(var op in ops)
{
string updatetQuery = "update sys.OP_difficulty set op_difficulty = #diff where op = #op;";
MySqlCommand updateCommand = new MySqlCommand(updatetQuery);
updateCommand.Connection = myConnection;
updateCommand.Parameters.AddWithValue("#diff", op.op_dif);
updateCommand.Parameters.AddWithValue("#op", op.op);
myConnection.Open();
int updatedRowNum = 0;
try
{
updatedRowNum = updateCommand.ExecuteNonQuery();
}
catch(MySqlException)
{
updatedRowNum = updateCommand.ExecuteNonQuery();
}
finally
{
myConnection.Close();
}
res = "{status:SUCCESS, updatedRowNum:" + updatedRowNum + "}";
}
return res;
}
Controller where it reads the view query:
public string UpdateOp()
{
string data = Request.Form["data"];
IQA sys = new MysqlSys();
try
{
var rows = JsonConvert.DeserializeObject<operation[]>(data);
return sys.UpdateOpsDiff(rows);
}
catch (JsonSerializationException je)
{
Console.WriteLine(je.Message);
return "{status:'DATA_FORMAT_ERROR'}";
}
}
Is there any missing items that I need. It already working using the query from my controller but this time I need to store my query from my view.
Any suggestions or comments. TIA
Since you're using AJAX callback, you should change return type to ActionResult and mark the action method with [HttpPost] attribute, also you should use return Content() or return Json() depending on returned type from UpdateOpsDiff() (string or object, respectively). Here is an example of proper setup:
[HttpPost]
public ActionResult UpdateOp(string data)
{
IQA sys = new MysqlSys();
try
{
var rows = JsonConvert.DeserializeObject<operation[]>(data);
string result = sys.UpdateOpsDiff(rows);
// return JSON-formatted string should use 'Content()', see https://stackoverflow.com/q/9777731
return Content(result, "application/json");
}
catch (JsonSerializationException je)
{
// do something
return Json(new { status = "DATA_FORMAT_ERROR"});
}
}
Then set the AJAX callback to pass JSON string into action method mentioned above:
$('#btnSave').click(function () {
op = $('#op').val();
op_dif = $('#op_difficulty').val();
var values = { op: op, opDiff: op_dif };
$.post("/Home/UpdateOP", { data: JSON.stringify(values) }, function (data) {
var resp = JSON.parse(data);
if (resp["status"] == "SUCCESS") {
alert('Data has been successfully updated');
location.reload();
}
else {
alert('Error!!');
}
});
});
Note:
The JSON-formatted string should be presented in key-value pairs to be returned as content, as shown in example below:
res = string.Format(#"{""status"": ""SUCCESS"", ""updatedRowNum"": ""{0}""}", updatedRowNum);

calling objects of functions in constructor in javascript

guys i know it is dummy question but i tried a lot and never reached .. here is my code in jsp
<button type="button" onclick="loadDepartment();" id="dep">Departments</button>
function deleteDep(id){
$.ajax({
url : '/Spring3HibernateApp1/deleteDep',
type : 'GET',
data : {
"id" : id,
},
dataType : "json"
});
}
function loadDepartment(){
$( document ).ready(function() {
$.ajax({
url : '/Spring3HibernateApp1/indexDep',
type : 'GET',
error : function(that, e) {
alert(e);
},
success : function(data) {
var newData = data.MyListDep;
gridDep = new GridLibraryDep({data: newData, deletefunction: deleteDep(id)});
gridDep.display();
}
});
});
}
and in JS
function GridLibraryDep(data, deletefunction) {
this.data = data.data;
this.deletefunction = deletefunction.deletefunction(id);
}
GridLibraryDep.prototype = {
deleteRow : function() {
$("input:checkbox:checked").each(bindContext(function(index, item) {
var str = $(item).attr("id");
str = str.substring(str.indexOf("_") + 1);
var id = this.data[str][this.columns[1]];
this.deletefunction(id);
this.data.splice(str, 1);
this.deleteTable();
this.display();
}, this));
}}
i want to access the deletefunction in jsp and use it in js .. but it gives em id not defined in jsp .. any suggestions ??
You are doing it overcomplicated and wrong.
Correct this line:
gridDep = new GridLibraryDep({data: newData, deletefunction: deleteDep(id)});
to:
gridDep = new GridLibraryDep(newData, deleteDep);
And the constructor:
function GridLibraryDep(data, deletefunction) {
this.data = data.data;
this.deletefunction = deletefunction.deletefunction(id);
}
to:
function GridLibraryDep(data, deletefunction) {
this.data = data;
this.deletefunction = deletefunction;
}
Now the declared and passed parameters match and the function is passed instead of function call result.

Javascript list passing to c#

I have a Asp.net MVC program in which i want to get a list from the View using Javascript and pass that list to the controller. I want to the variables in the list to be string type except for one to be int32.
The problem is the list is either empty or does not pass.
I tried to use stringify but it doesn't fill the requirments.
Here is the code from the javascript part:
$('#AddColumn').click(function () {
var nodeURL = document.getElementById("IDHolder").innerHTML;
var nodeConfig= nodeURL+".CONFIG";
var nodeAdd=nodeURL+".CONFIG.AddColumn";
var nodeName = $("#ColumnName").val();
var nodeType = $("#ColumnType").data("kendoComboBox").value();
var ListNodedet = [nodeName, nodeType];
var Listmet = [nodeConfig, nodeAdd];
var ListNodeDetails = JSON.stringify(ListNodedet);
var ListMethod = JSON.stringify(Listmet);
var select = 1;
var url = "/Configuration/CallMethod";
$.get(url, { ListNodeDetails:ListNodeDetails, ListMethod:ListMethod }, function (data) {
$("#Data2").html(data);
});
})
The C# code for the controller were it calls another method in models:
public bool CallMethod(List<Variant> ListNodeDetails, List <string> ListMethod)
{
var AddMethod = RxMUaClient.CallMethod(ListNodeDetails, ListMethod, "127.0.0.1:48030");
return AddMethod;
}
The Model:
public static bool CallMethod(List<Variant> ListNodeDetails, List<string> ListMethod, string iPAddress)
{
var serverInstance = GetServerInstance(iPAddress);
if (serverInstance == null)
return false;
return serverInstance.CallMethod(ListNodeDetails, ListMethod);
}
The service model
public bool CallMethod(List<Variant> ListNodeDetails, List<string> ListMethod)
{
try
{
if (_mSession == null)
{
return false;
}
NodeId objectID = NodeId.Parse(ListMethod[0]);
NodeId Methodtype = NodeId.Parse(ListMethod[1]); ;
List<Variant> inputArguments = ListNodeDetails;
List<StatusCode> inputArgumentErrors = null;
List<Variant> outputArguments = null;
StatusCode error = _mSession.Call(
objectID,
Methodtype,
inputArguments,
new RequestSettings() { OperationTimeout = 10000 },
out inputArgumentErrors,
out outputArguments);
if (StatusCode.IsBad(error))
{
Console.Write("Server returned an error while calling method: " + error.ToString());
return false;
}
return true;
}
catch (Exception exception)
{
Console.WriteLine(exception.ToString());
return false;
}
}
At the end it calls some functions using OPC UA to add data.
I have changed it to be ajax function and it works well but only with one list form the lists passed to the method!
I dont know if this is because i read values from kendo box and text box, and they are different types but i tried to stringfy it and it still does not work. On the console both lists are out as strings. So still got a problem with passing the first List "ListNodeDetails"!
$('#AddColumn').click(function () {
var nodeURL = document.getElementById("IDHolder").innerHTML;
var nodeConfig= nodeURL+".CONFIG";
var nodeAdd=nodeURL+".CONFIG.AddColumn";
var nodeName = $("#ColumnName").val().toString();
var nodeType = $("#ColumnType").data("kendoComboBox").value().toString();
var ListNodedet = [nodeName, nodeType];
var Listmet = [nodeConfig, nodeAdd];
var params = {
ListNodeDetails: ListNodedet,
ListMethod: Listmet
};
var url = "/Configuration/CallMethod";
console.log(params); // added sanity check to make sure data is correctly passed
var temp = {
url: "/Configuration/CallMethod",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(params),
success: function (params) {
window.location.replace(params.redirect);
}
};
$.ajax(temp);
})

How to filter JSON data for autosuggestion using Ajax (without jQuery ui)

I am trying to create an auto-suggestion from scratch. I am using canjs controller to control the DOM elements (ul and li).
I want smart and short code to implement this. I have tried with filter but I want Ajax filter method to use for this purpose.
I have tried the following thing:
can.Model:
var SearchDomainModel = can.Model.extend({
findAll: function(){
return this.getDomains;
}
}, { domainList: null,
getDomains: function(params, callback) {
var promise = $.ajax({
url: '/scripts/models/domains.json',
type: 'GET',
dataType: 'json',
dataFilter: function(data, type){
var parsed_data = JSON.parse(data);
var regex = new RegExp(params, 'gi')
var temp = [];
$.each(parsed_data, function(i, item){
for(var j in item)
if ((item[j].url).toLowerCase().indexOf(params) >= 0){
temp.push(item[j].url);
console.log(temp);
}
});
return temp;
}
});
This is my can.controller:
var DomainController = can.Control.extend({
defaults: {
view: 'views/domainSearch.hbs'
}
}, {
searchList: new can.List(),
domainModel: new DomainModel(),
init: function(element, options) {
this.element.html(can.view(this.options.view, this.searchList));
$('html,body').css({
percentWidth: 100,
percentHeight: 100
});
$('.error').hide();
}, // control domain filter on keyup event
'input keyup': function(element, event) {
var self = this;
var searchText = element.val();
if (searchText !== "") {
this.domainModel.getDomains(searchText, function (response, error) {
self.searchList.attr("domains",response);
console.log(error);
})
I am trying and searching from last two days. I could not have done it. Can anybody suggest me where is my mistake in the code and how to solve it?
Thanx in advance!!
I would probably do something like this:
var SearchDomainModel = can.Model.extend({
findAll: function(){
return this.getDomains;
}
}, { domainList: null,
getDomains: (function() {
var domains = null;
function search(searchText, callback){
var regex = new RegExp(searchText, 'gi')
var temp = [];
$.each(domains, function(i, item){
for(var j in item)
if (regex.test(item[j].url))
temp.push(item[j].url);
});
callback(temp);
}
return function(searchText, callback) {
if( domains ) {
search(searchText, callback);
return;
}
$.ajax({
url: '/scripts/models/domains.json',
type: 'GET',
dataType: 'json',
success: function(data) {
domains = data;
search(searchText, callback);
}
});
};
})()
});
I didn't test the code but it doesn't spawn one ajax request everytime you release a key but instead grabs the data once and then refers to the same data.

Post Javascript Array to WebAPI

I wanted to post a Javascript Array to a WebAPI.
I have my Javascript Array like:
var checkedGroups = [];
var checkedStaff = [];
$.each(items, function () {
if (this.checked) {
type = dataAdapter.records[this.id - 1].VALUETYPE;
if (type == 'Staff') {
checkedStaff[checkedStaff.length] = this.value;
} else {
checkedGroups[checkedGroups.length] = this.value;
}
}
});
I am then sending this to my WebAPI using this:
data: { staff: JSON.stringify(checkedStaff) };
My WebAPI Controller is then like:
public HttpResponseMessage Post([FromBody] formData data)
{
string string_group = String.Join(",", data.group);
string string_staff = String.Join(",", data.staff);
}
and my formData class is this:
public class formData
{
public Array group { get; set; }
public Array staff { get; set; }
}
As per above, I would like to split the array out to make a comma delimerated string.
But string_staff variable on the server side is just an empty string and my JSON data was this:
staff: "["1"]"
group: ""
I do not want to use key/value types in the array either.
Any idea's?
Change checkedGroups and checkedStaff variables to object literals. There's not really such a thing as an associative array in Javascript the way you're trying to set it.
var checkedGroups = {};
var checkedStaff = {};
$.each(items, function () {
if (this.checked) {
type = dataAdapter.records[this.id - 1].VALUETYPE;
if (type == 'Staff') {
checkedStaff[checkedStaff.length] = this.value;
} else {
checkedGroups[checkedGroups.length] = this.value;
}
}
});
You could keep them as arrays if you do:
checkedStaff.push(this.value);
Generally, you should use jQuery ajax function $.ajax({ ... }) to post to WebAPI controller. I have found this method works the best:
function postJSON(data)
{
return $.ajax({
url: '/api/xyz',
type: 'POST',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8" // must have this option set
});
}
function doSomethingElse() {
postJSON({ staff: checkedStaff, group: checkedGroup })
.done(function(response) { ... });
}

Categories