ASP.NET MVC ADO.NET Query per table row - javascript

Here I have this table:
If I click the button, I want to pass the table per row to the controller, then perform ADO.NET Query per row, like for example, perform "UPDATE tbluser SET note='INACTIVE' WHERE id=#id" per row.
One of the main purpose of this is when i filter the table, only the visible rows will be passed.
I already have a code here to pass to controller using AJAX but I don't know what to do afterwards.
JS:
var HTMLtbl =
{
getData: function (table) {
var data = [];
oTable.rows({ search: 'applied' }).every(function () {
var cols = [];
var rowNode = this.node();
$(rowNode).find("td").each(function () {
cols.push($(this).text().trim() || null);
});
data.push(cols);
});
return data;
}
}
$("btnSubmit").on("click", function () {
var data = HTMLtbl.getData($(".datatable"));
var parameters = {};
parameters.array = data;
var request = $.ajax({
async: true,
cache: false,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Home/SubmitTable",
data: JSON.stringify(parameters),
success: function () {
window.location.href = "/Home/Index";
}
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
Controller:
[HttpPost]
public JsonResult SubmitTable(string[][] array)
{
//I don't know what to do here now, please help
}
My Solution based on Mostafa's answer:
JS:
var HTMLtbl =
{
getData: function () {
var data = [];
oTable.rows({ search: 'applied' }).every(function () {
var cols = [];
var rowNode = this.node();
$(rowNode).find("td").each(function () {
cols.push($(this).text().trim() || null);
});
data.push(cols);
});
return data;
}
}
$("#btnSubmit").on("click", function () {
var data = HTMLtbl.getData($(".datatable"));
var parameters = {};
parameters.array = data;
var request = $.ajax({
async: true,
cache: false,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Home/SubmitTable",
data: JSON.stringify(parameters),
success: function () {
window.location.href = "/Home/Index";
}
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
Controller:
[HttpPost]
public JsonResult SubmitTable(string[][] array)
{
string result = string.Empty;
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
con.Open();
foreach (var arr in array)
{
SqlCommand cmd = new SqlCommand("UPDATE tbluser SET remark='INACTIVE' WHERE id = #id", con);
cmd.Parameters.AddWithValue("#id", arr[0]);
cmd.ExecuteNonQuery();
}
con.Close();
}
catch (Exception ex)
{
result = ex.Message;
}
return Json("Records updated successfully.", JsonRequestBehavior.AllowGet);
}
I can now use this for more complicated stuff, thanks

If you want to update a custom row you can add a button for each row with custom text and icon, then add a "data-" attribute to this button and path your row id,
<input type="button" data-rowId="1" class="changeActivationState">activate</input>
in this example I added a data field to my imput after that I define this javascript method:
$(".changeActivationState").click(function(){
$(this).data("rowId")//get the selected row id and call you service
});
using this code you can read first element for each row and perform a web service call for all rows
var arr = [];
$("#yourtable tr").each(function(){
arr.push($(this).find("td:first").text()); //put elements into array
});
and using this code you can read all rows into a json object
var tbl = $('#yourtable tr').map(function() {
return $(this).find('td').map(function() {
return $(this).html();
}).get();
}).get();
assume that you passed the list to action
int[] passedIDsfromBrowser = ///filled with data that comes from browser;
SqlConnection connection = ....
SqlCommand command = new SqlCommand(connection);
command.CommandText = "Update MYTABLENAME Set Active = true where ID in (" string.Join(",", passedIDsfromBrowser ) + ")";
connection.Open();
command.ExecuteNonQuery();
connection.Close();
this is a pseudo code.
or if you want a loop and updating each row with a loop
SqlConnection connection = ....
SqlCommand command = new SqlCommand(connection);
connection.Open();
for(int i = 0 ; i < passedIDsfromBrowser.Length; i++){
command.CommandText = "YOURQUERY";
command.ExecuteNonQuery();
}
connection.Close();

Related

Cannot show value after AJAX call (ASP.NET MVC)

I have two <p> fields where I need to assign text
Here is html code:
<p id="appId" style="visibility: hidden;"></p>
<p id="calculationId" style="visibility: hidden;"></p>
I make AJAX call like this
$('#openCalculationConsumables').click(function() {
addConsumables();
});
function addConsumables() {
var patientName = $('#patientsId').val();
var finding = $('#findingvalue').val();
var procedure = $('#procedurevalue').val();
var model = {
findingValue: finding,
procedureValue: procedure,
patientId:patientName
}
$.ajax({
url: '#Url.Action("AddIndividualCalculation", "Calculations")',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(model),
type: 'POST',
dataType: 'json',
processData: false,
success: function (data) {
$('#masters_data').load('#Url.Action("IndividualCalculationConsumables", "Calculations")', function() {
var list = data;
$('#calculationId').text(list[0].calcid);
$('#appId').text(list[0].appid);
});
}
});
}
And here is my back end code:
public JsonResult AddIndividualCalculation(string findingValue, string procedureValue,int patientId)
{
using (var ctx = new ApplicationDbContext())
{
Calculation calc = new Calculation
{
};
ctx.Calculations.Add(calc);
ctx.SaveChanges();
int calculationId = calc.Id;
Appointment app = new Appointment
{
Calculation_id = calculationId,
FindingContent = findingValue,
ProcedureContent = procedureValue,
Patient_id = patientId
};
ctx.Appointments.Add(app);
ctx.SaveChanges();
int appointmentId = app.Id;
var items = new
{
appid = appointmentId,
calcid = calculationId
};
return Json(items,JsonRequestBehavior.AllowGet);
}
}
I set breakpoint and see , that I have values in items. In console log I have this {appid: 1006, calcid: 1006}
But I cant assign it to <p> and have this error.
Cannot read property 'calcid' of undefined
Where is my problem?
Thank's for help.
$('#masters_data').load('#Url.Action("IndividualCalculationConsumables", "Calculations")', function() {
var list = data;
$('#calculationId').text(list[0].calcid);
$('#appId').text(list[0].appid);
});
list[0] is not defined as you are returning just an anonymous object not a list of objects
new {
appid = appointmentId,
calcid = calculationId
};

Trying to Bind the gridview but after binding data and rows both disappear

I' m trying to bind a gridview using Ajax jquery.while I saw the data is bind with gridview and shown in the browser but after completion of debugging .all data that fill up the rows goes disappear.Trying to find out the issue but after execution of $("#THistory").click(function () { this function the debugger goes to Page_Load method
Ajax part
<%--GridView Populate--%>
<script type="text/javascript">
$(function () {
$("#THistory").click(function () {
$.ajax({
type: "POST",
url: "TDC.aspx/GetCustomers",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
});
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var customers = xml.find("Table");
var row = $("[id*=gvCustomers] tr:last-child").clone(true);
$("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove();
$.each(customers, function () {
var customer = $(this);
$("td", row).eq(0).html($(this).find("REVISION").text());
$("td", row).eq(1).html($(this).find("P_GROUP").text());
$("[id*=gvCustomers]").append(row);
row = $("[id*=gvCustomers] tr:last-child").clone(true);
});
}
});
</script>
<%--GridView Populate--%>
.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindDummyRow();
}
}
private void BindDummyRow()
{
DataTable dummy = new DataTable();
dummy.Columns.Add("REVISION");
dummy.Columns.Add("P_GROUP");
dummy.Rows.Add();
gvCustomers.DataSource = dummy;
gvCustomers.DataBind();
//gvCustomers.Visible = false;
}
[WebMethod]
public static string GetCustomers()
{
string query = "SELECT REVISION, P_GROUP from tdc_product1 ";
OracleCommand cmd = new OracleCommand(query);
return GetData(cmd).GetXml();
}
private static DataSet GetData(OracleCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["conndbprodnew"].ConnectionString;
using (OracleConnection con = new OracleConnection(strConnString))
{
using (OracleDataAdapter sda = new OracleDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}

Cannot POST more than one value with AJAX

I stucked on one thing. I have a 2 grid inside checkboxes. When I selected that checkboxes I want to POST that row data values like array or List. Actually when i send one list item it's posting without error but when i get more than one item it couldn't post values.
Example of my grid
Here my ajax request and how to select row values function
var grid = $("#InvoceGrid").data('kendoGrid');
var sel = $("input:checked", grid.tbody).closest("tr");
var items = [];
$.each(sel, function (idx, row) {
var item = grid.dataItem(row);
items.push(item);
});
var grid1 = $("#DeliveryGrid").data('kendoGrid');
var sel1 = $("input:checked", grid1.tbody).closest("tr");
var items1 = [];
$.each(sel1, function (idx, row) {
var item1 = grid1.dataItem(row);
items1.push(item1);
});
$.ajax({
url: '../HeadOffice/CreateInvoice',
type: 'POST',
data: JSON.stringify({ 'items': items, 'items1': items1, 'refnum': refnum }),
contentType: 'application/json',
traditional: true,
success: function (msg) {
if (msg == "0") {
$("#lblMessageInvoice").text("Invoices have been created.")
var del = $("#InvoiceOKWindow").data("kendoWindow");
del.center().open();
var del1 = $("#InvoiceDetail").data("kendoWindow");
del1.center().close();
$("#grdDlvInv").data('kendoGrid').dataSource.read();
}
else {
$("#lblMessageInvoice").text("Problem occured. Please try again later.")
var del = $("#InvoiceOKWindow").data("kendoWindow");
del.center().open();
return false;
}
}
});
This is my C# part
[HttpPost]
public string CreateInvoice(List<Pm_I_GecisTo_Result> items, List<Pm_I_GecisFrom_Result> items1, string refnum)
{
try
{
if (items != null && items1 != null)
{
//do Something
}
else
{
Log.append("Items not selected", 50);
return "-1";
}
}
catch (Exception ex)
{
Log.append("Exception in Create Invoice action of HeadOfficeController " + ex.ToString(), 50);
return "-1";
}
}
But when i send just one row it works but when i try to send more than one value it post null and create problem
How can i solve this? Do you have any idea?
EDIT
I forgot to say but this way is working on localy but when i update server is not working proper.
$.ajax({
url: '../HeadOffice/CreateInvoice',
type: 'POST',
async: false,
data: { items: items, items1: items1 }
success: function (msg) {
//add codes
},
error: function () {
location.reload();
}
});
try to call controller by this method :)

upload data to server from javascript to php using ajax

I need to upload websql table to the server using ajax.
when I use indexed array or simple variable code works fine.
I cant figure out what problem is? plz help me.
thanks in advance...
here is javascript:
function upload()
{
var db = cropsap.webdb.db;
db.transaction(function (tx) {
tx.executeSql('SELECT * from survey', [],function(tx, results) {
var data = "";
var survey=[];
for(var i=0; i < results.rows.length; i++) {
var row = results.rows.item(i);
var result = [];
for(var key in row)
{
result[key] = row[key];
}
survey.push(result);
}
//alert(survey[0]['srno']);//here i get output
var url = "";
url = document.getElementById("url").value;
$.ajax({
type: "POST",
url: url,
async: true,
data: { "data": JSON.stringify(survey) },
error: function () { alert("error occured");},
success: function (data) {
alert("sucess");
alert(data);
}
});
});
});
}
php code:
<?php
$survey= json_decode(stripslashes($_POST['data']));
$len = sizeof($crop_insect_survey_details);
print(" len: ".$len);
for($i=0;$i<$len;$i++)
{
$srno = $crop_insect_survey_details[$i]['srno'];//here cant get output
$name = $crop_insect_survey_details[$i]['name'];
print("srno:".$srno);
print("name:".$name);
}
?>
Instead of using data: { "data": JSON.stringify(survey) }, You can pass your data inside data key itself.
data:JSON.stringify(survey)
dataType: "json",
contentType: "application/json; charset=utf-8",

A script for upadate textbox's value in asp.net mvc didn' work

I want to update textbox's value(that contains cookie's value) using Ajax in asp.net MVC5 . I'm very new in JavaScript and I wrote these codes , but my code didn't work . I didn't get any error but it's not working. I wrote JavaScript in foreign file 'UpdateTxtBox.js' and I added <script src="~/Scripts/UpdateTxtBox.js"></script> to Layout .
Could anyone tell me what's the problem ?
$(function () {
$("textCountProduct").change(function () {
var count = $(this).val();
var id = $(this).attr("productid");
$.ajax({
url: "/Goods/AddToCart",
data: { Id: id, Count: count },
type: "Post",
dataType: "Json",
success: function (result) {
if (result.Success) {
alert(result.Html);
$("#CartItems").html(result.Html);
}
eval(result.Script);
},
error: function () {
alert("error....");
}
});
});
});
a part of Basket.cshtml
#using (Html.BeginForm("AddToCart", "Goods", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.TextBoxFor(modelItem => item.Count, new { #class="text textCountProduct" , style="width:40px;" , productid=item.GoodDetails.DetailsGoodID})
}
Good controller
public ActionResult AddToCart (int Id , int Count)
{
try
{
if (Request.Cookies.AllKeys.Contains("NishtmanCart_" + Id.ToString()))
{
//Edit cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), (Convert.ToInt32(Request.Cookies["NishtmanCart_" + Id.ToString()].Value) + 1).ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Set(cookie);
}
else
{
//Add new cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), Count.ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
}
List<HttpCookie> lst = new List<HttpCookie>();
for (int i = 0; i < Request.Cookies.Count; i++ )
{
lst.Add(Request.Cookies[i]);
}
bool isGet = Request.HttpMethod == "GET";
int CartCount = lst.Where(p => p.Name.StartsWith("NishtmanCart_") && p.HttpOnly != isGet).Count();
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("Good added successfully", MessageType.Success).Script,
//Script = "alert('Good added successfully');",
Html = "cart items (" + CartCount.ToString() + ")"
}
);
}
Update post :
I added [HttpPost] to controller action result and add some alert to javascript
$(function () {
alert("aleeeert");
$(".textCountProduct").change(function () {
var count = $(this).val();
var id = $(this).attr("productid");
alert(count);
alert(id);
$.ajax({
url: "/Goods/AddToCart",
data: { Id: id, Count: count },
type: "Post",
dataType: "Json",
success: function (result) {
if (result.Success) {
alert(result.Html);
$("#CartItems").html(result.Html);
}
eval(result.Script);
},
error: function () {
alert("error....");
}
});
});
});
it's working fine but when I refresh page , data didn't saved
Since you have specified textCountProduct as CSS class, you need to prefix it with . to use Class Selector (“.class”), As of now its looking for Element textCountProduct which obviously doesn't exists.
Use
$(".textCountProduct").change(
You have made mistake here $("textCountProduct") use . as selector.
It should be $(".textCountProduct")
and
Check path of your script included
<script src="~/Scripts/UpdateTxtBox.js"></script>

Categories

Resources