Trying to sort repeater rows with this jQuery - javascript

I am trying to sort repeater rows with this jquery . But I am not able to save sort items. Please help me . how can save sorting in database as well as in .aspx page?Thank you in advance
<script language="javascript" type="text/javascript">
$("#defaultList").sortable();
$(document).ready(function () {
$("#defaultList").sortable(
{
update: function (ev, ui) {
var result = $('#defaultList').sortable('toArray');
updateSequenceNumber(result);
}
}
);
});
function updateSequenceNumber(items) {
var originalIdAndSequenceNumber = '';
var index = 0;
for (i = 0; i <= items.length - 1; i++) {
if (items[i].length == 0)
continue;
var item = $('#' + items[i])[0];
originalIdAndSequenceNumber += item.attributes["originalId"].nodeValue + ":" + index.toString();
originalIdAndSequenceNumber += "|";
index = index + 1;
}
persistPositionUsingAjax(originalIdAndSequenceNumber);
}
function persistPositionUsingAjax(originalIdAndSequenceNumber) {
$.ajax(
{
type: "POST",
dataType: "text",
url: "AjaxService.asmx/UpdateSequenceNumber",
data: "s=" + originalIdAndSequenceNumber,
success: function (response) {
}
}
);
}
my ajax method:
[WebMethod]
public string UpdateSequenceNumber(string s)
{
s = s.TrimEnd('|');
string updateQuery = #"update dnn_Table_1 set SortId = {0}
where ImageId = {1}";
StringBuilder sb = new StringBuilder();
string[] originalIdAndSeqNumberArray = s.Split('|');
foreach (var originalIdAndSeqNumberCombined in originalIdAndSeqNumberArray)
{
var tempArray = originalIdAndSeqNumberCombined.Split(':');
int originalId = Convert.ToInt32(tempArray[0]);
int sequenceNumber = Convert.ToInt32(tempArray[1]);
sb.Append(String.Format(updateQuery, sequenceNumber, originalId));
sb.Append(System.Environment.NewLine);
}
UpdateInDatabase(sb.ToString());
return "Hello World";
}
private void UpdateInDatabase(string updateQuery)
{
SqlDataProvider sqd = new SqlDataProvider();
string ConnectionString = sqd.ConnectionString;
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand command = new SqlCommand(updateQuery, conn);
command.CommandText = updateQuery;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}

What status code does the ajax call return?
To me it looks like a 500. You are building an update statement that after a few iterations will look something like this
update dnn_Table_1 set SortId = 3 where ImageId = 2update dnn_Table_1 set SortId = 2 where ImageId = 4update dnn_Table_1 set SortId = 7 where ImageId = 6
That just won't work. Try eihter constructing the SQL update differently or move UpdateInDatabase into the foreach loop.
There might be other issues which I didn't spot, but this might be a starting point.
Hope that helps

Related

Save text from javascript variable to .txt file

I am trying this code, but can't get it to work, it says "The name "text" does not exist in the current context"
CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("for(var i = 0; i < elems1.length; i++){ var textt = elems1[i].innerText}");
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true))
{
outputFile.WriteLine(textt);
}
How can I make variable "textt" accessible?
Here is a full code:
private void button3_Click(object sender, EventArgs e)
{
CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("var elems1 = document.getElementsByClassName('question-text')");
CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("for(var i = 0; i < elems1.length; i++){var textt = elems1[i].innerText}");
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true))
{
outputFile.WriteLine(textt);
}
}
You might be looking for ContinueWith() which can be chained after ExecuteJavaScriptAsync().
In this example you need to use your JavaScript code as a function which returns anything (ex. textt). So I've created something like this:
var myScript = #"(function () {
var textt = "";
var elems1 = document.getElementsByClassName('question-text');
for(var i = 0; i < elems1.length; i++){
textt += elems1[i].innerText
}
return textt;
})();";
than I asynchronously evaluate it and catch the result which I am returning from that function:
var result = await CurBrowser
.GetMainFrame()
.EvaluateScriptAsync(myScript)
.ContinueWith(t => {
var result = t.Result; // your textt
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true)) {
outputFile.WriteLine(result);
}
});
this is just a suggestion of how it might work.

insert razor code in ajax

I'm using ASP.Net MVC with EF6, I did paging by Skip and Take method like this in my controller
private const int PageSize = 6;
public JsonResult GetSearchingData(string SearchBy, string SearchValue, int page = 1)
{
Entities db = new Entities();
if (SearchBy == "Name")
{
ViewBag.CurrentPage = page;
ViewBag.PageSize = PageSize;
int p = page - 1;
ViewBag.CurrentPage = page;
ViewBag.PageSize = PageSize;
List<MyTable> SupList = new List<MyTable>();
SupList = db.MyTable.Where(x => x.Name.Contains(SearchValue) || SearchValue == null).ToList();
var subCategoryToReturn = SupList.Select(S => new { Name = S.Name });
ViewBag.TotalPages = Math.Ceiling(((double)subCategoryToReturn.Count()) / PageSize);
var temp =subCategoryToReturn.ToList().Skip(p * PageSize).Take(PageSize);
return Json(temp, JsonRequestBehavior.AllowGet);
}
else
return Json(new EmptyResult(), JsonRequestBehavior.AllowGet);
}
how can I add paging links in JavaScript?
I tried to add this Razor code in ajax to display page number, but it is impossible to add Razor in ajax
#for(int i = 1; i <= ViewBag.TotalPages; i++) { <
a href = "#Url.Action("
GetSearchingData ","
MyControllerName ", new { page = i } )" > #i < /a>
}
$(document).ready(function() {
$("#Search").keydown(function() {
var SearchBy = $("#SearchBy").val();
var SearchValue = $("#Search").val();
//SearchData is the div name to append the result of ajax to html
var SetData = $("#SearchData");
SetData.html("");
$.ajax({
//some code
url: "/MyControllerName/GetSearchingData?SearchBy=" + SearchBy + "&SearchValue=" + SearchValue,
success: function(result) {
//Receive the filtering data from controller and show it for user
$.each(result, function(index, value) {
var Data = '<div class="col-sm-3" ><div class="card"><canvas id="header-blur"></canvas><div class="avatar"></div><div class="content"> <p>' +
value.Name + '</p></div></div></div>';
SetData.append(Data);
});
//here is my question how to add this Razor code to ajax ?
SetData.append(
#for(int i = 1; i <= ViewBag.TotalPages; i++) { <
a href = "#Url.Action("
GetSearchingData ","
MyControllerName ", new { page = i } )" > #i < /a>
}
);
}
}
});
});
});
Razor formatting can get very tricky. In this case, you'll have to try and keep all of this on one line. Give it a try:
#for(int i = 1; i <= ViewBag.TotalPages; i++)
{
#:" #i ";
}
edit: If it spits out encoded HTML, you can also do it this way:
#Html.Raw(" #i ")

How to append div by ajax

i'm trying to retrieve values from database after that how can i pass those values from that static method and append to div in ajax ,Here is the C# code for that
[WebMethod]
[ScriptMethod]
public static string[] Cdetails(Cmpny cmpny)
{
StringBuilder html = new StringBuilder();
string strCname = cmpny.Cname;
string strCvalue= cmpny.Cvalue;
string strLvl = cmpny.Clevel;
int intLvl = Convert.ToInt32(strLvl);
List<string> company = new List<string>();
if (intLvl == 1)
{
SqlConnection conn = new SqlConnection(HttpContext.Current.Session["ConnectionString"].ToString());
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Clientid,C_Name,C_website,Status,CreatedDate,CreatedBy,ModifiedDate,ModifiedBy from clientDetails where Clientid=#Clientid and C_Name=#C_Name";
cmd.Parameters.AddWithValue("#C_Name", strCname);
cmd.Parameters.AddWithValue("#Clientid", strCvalue);
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
company.Add(string.Format("{0}-{7}", sdr["Clientid"], sdr["C_Name"], sdr["C_website"], sdr["Status"], sdr["CreatedDate"], sdr["CreatedBy"], sdr["ModifiedDate"], sdr["ModifiedBy"]));
}
}
conn.Close();
}
}
//else
//{
// return strLvl.ToArray();
//}
return company.ToArray();
}
and ajax method is here
<script type="text/javascript">
function OnTreeClick(evt) {
var src = window.event != window.undefined ? window.event.srcElement : evt.target;
var nodeClick = src.tagName.toLowerCase() == "a";
if (nodeClick) {
var nodeText = src.innerText || src.innerHTML;
var nodeValue = GetNodeValue(src);
var nodePath = src.href.substring(src.href.indexOf(",") + 2, src.href.length - 2);
//alert(nodePath.toLowerCase());
if (nodePath.indexOf("\\") > -1)
{
var level = "2";
// alert("Second level ");
}
else
{
var level = "1";
// alert(" first level ");
}
//var nodestat =
alert("Text: " + nodeText + "," + "Value: " + nodeValue );
var cmpny = {};
cmpny.Cname = nodeText;
cmpny.Cvalue = nodeValue;
cmpny.Clevel = level;
$.ajax({
type: "POST",
url: "CS.aspx/Cdetails",
data: '{cmpny: ' + JSON.stringify(cmpny) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
div_ClientLoc.innerHTML = response.d;//here how can i append those tag and div_ClientLoc is div id
// window.location.reload();
}
});
return false;
}
return true;
}
function GetNodeValue(node) {
var nodeValue = "";
//alert(node.href.toLowerCase());
var nodePath = node.href.substring(node.href.indexOf(",") + 2, node.href.length - 2);
// alert(nodePath.toLowerCase());
var nodeValues = nodePath.split("\\");
if (nodeValues.length > 1)
nodeValue = nodeValues[nodeValues.length - 1];
else
nodeValue = nodeValues[0].substr(1);
return nodeValue;
}
can anyone please explain me how can i solve this problem
You are overwriting the html of div_ClientLoc by assigning the result to innerHTML. You can use jQuery append() method to append the response result in existing html of div_ClientLoc.
$("#div_ClientLoc").append(response.d);
Or you can also append the result in div_ClientLoc.innerHTML by using Addition Assignment Operator += instead of assignment operator = like as under
div_ClientLoc.innerHTML += response.d;
You need to get a hold of the element that you are appending to, then insert the HTML.
You can use document.getElementById('div_ClientLoc') to get your target element.
insertAdjacentHTML will insert the content at beforeend, which is before the closing tag.
document.getElementById('div_ClientLoc').insertAdjacentHTML('beforeend', response.d);

C# in javascript executes only once

When I try to read the data from Azure Database code does so correctly on page load/refresh but then it repeats the very same data, even though I call a function to get a new one.
C# Code for fetching data.
public static class GetSensorData
{
public static List<Reading> GetTemperatureSensorData(int quantity)
{
decimal TemperatureCelcius;
DateTime TimeOfAReading;
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["rpiDB"].ConnectionString.ToString();
List<Reading> TempTemperatureList = new List<Reading> { };
SqlConnection Connection = new SqlConnection(ConnectionString);
SqlCommand GetTemperature = new SqlCommand("SELECT TOP " + quantity + " * FROM tbl_temp ORDER BY time DESC;", Connection);
Connection.Open();
SqlDataAdapter TempAdapter = new SqlDataAdapter(GetTemperature);
DataTable TempereatureSensorDataTable = new DataTable();
TempAdapter.Fill(TempereatureSensorDataTable);
for (int i = 0; i < quantity; i++)
{
TemperatureCelcius = (decimal)TempereatureSensorDataTable.Rows[i][0];
//gotta change the culture from within
TemperatureCelcius = decimal.Parse(TemperatureCelcius.ToString(), CultureInfo.InvariantCulture);
TimeOfAReading = (DateTime)TempereatureSensorDataTable.Rows[i][1];
TempTemperatureList.Add(new Reading(TemperatureCelcius, TimeOfAReading.ToString("HH/mm")));
}
Connection.Close();
return TempTemperatureList;
}
}
And here's how I use it in CSHTML
var updateData = function (oldData) {
var labels = oldData["labels"];
var dataSetA = oldData["datasets"][0]["data"];
#{
List<Reading> SingleReading = new List<Reading>(GetSensorData.GetTemperatureSensorData(1));
}
var datetime = #SingleReading[0].TimeOfReading
labels.push(String(datetime));
labels.shift();
var Temperature = #(SingleReading[0].TemperatureCelcius);
dataSetA.push(Temperature / 100);
dataSetA.shift();
};
setInterval(function () {
updateData(data);
myLineChart.data = data;
myLineChart.update();
}, 5000
);
The function in setInterval is being executed every 5 seconds but with the data, I got on the page load.
You need to create a web service in your C# project so that you can make AJAX calls to GetTemperatureSensorData. I recommend putting this into its own Web API project. https://msdn.microsoft.com/en-us/library/hh833994(v=vs.108).aspx
Next, you will need to create an AJAX call to the web service in your javascript code. To make this easier to do, I recommend using the jQuery library, specifically the get command: https://api.jquery.com/jquery.get/
Thanks everyone for your help, I've figured it out.
This is my CS code from HomeController.cs
public ActionResult GetTemp(int quantity)
{
decimal TemperatureCelcius;
DateTime TimeOfReading;
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["rpiDB"].ConnectionString.ToString();
List<Reading> TempTemperatureList = new List<Reading> { };
SqlConnection Connection = new SqlConnection(ConnectionString);
SqlCommand GetTemperature = new SqlCommand("SELECT TOP " + quantity + " * FROM tbl_temp ORDER BY time DESC;", Connection);
Connection.Open();
SqlDataAdapter TempAdapter = new SqlDataAdapter(GetTemperature);
DataTable TempereatureSensorDataTable = new DataTable();
TempAdapter.Fill(TempereatureSensorDataTable);
for (int i = 0; i < quantity; i++)
{
TemperatureCelcius = (decimal)TempereatureSensorDataTable.Rows[i][0];
TimeOfReading = (DateTime)TempereatureSensorDataTable.Rows[i][1];
TempTemperatureList.Add(new Reading(TemperatureCelcius, TimeOfReading.ToString("HH:mm")));
}
Connection.Close();
return Json(TempTemperatureList, JsonRequestBehavior.AllowGet);
}
And Ajax:
setInterval(function () {
$.ajax({
type: 'GET',
url: '/Home/GetTemp',
contentType: 'application/json; charset=utf-8',
data: { 'quantity': 1 },
success: function (response) {
var _Temperature = response[0].TemperatureCelcius;
var _TimeOfReading = response[0].TimeOfReading;
console.log(_Temperature);
updateData(data, _Temperature, _TimeOfReading);
myLineChart.data = data;
myLineChart.update();
},
error: function(req, err){ console.log('my message ' + err); }
});
}, 5000
);

getting "undefined" when i print json array with js

I want to parse json array it came down from json.jsp, but when i access parse.js it displays undefined
Here is parse.js
$(document).ready(function() {
$('#login').click(function(event) {
$.get('json.jsp', {
}, function(responseText) {
var myJSONObject1 = responseText;
var myJSONObject = JSON.parse(myJSONObject1);
var len = myJSONObject.length;
var out = "";
for (var i = 0; i < len; i++) {
var student = myJSONObject[i];
out += "<li>"+student.ircEvent + "<li>" + student.method+"<li>"+student.regex;
}
document.getElementById("ajaxResponse").innerHTML = out;
});
});
});
and my json.jsp is,
<%
response.setContentType("plain/text");
User user = new User("RAM","ram#gmail.com");
User user1 = new User("Ravi","ravi#gmail.com");
User user2 = new User("Raghu","raghu#gmail.com");
List list = new ArrayList();
list.add(user);list.add(user1);list.add(user2);
String json = new Gson().toJson(list);
response.getWriter().write(json);
%>
when i access parse.js file, it displays undefined
any ideas......
Just use $.ajax and set the dataType to json. No need to parse anything. jQuery does it for you. http://api.jquery.com/jquery.ajax/
jQuery(document).ready(function($) {
$.ajax({
url: 'json.jsp',
type: 'get',
dataType: 'json',
success: function(data) {
if (data.length) {
var ajaxResponse = document.createElement('table'),
tbody = document.createElement('tbody');
for (var i in data) {
if (data.hasOwnProperty(i)) {
var tr = document.createElement('tr'),
key = document.createElement('td'),
keyText = document.createTextNode(i),
value = document.createElement('td'),
valueText = document.createTextNode(data[i]);
key.appendChild(keyText);
tr.appendChild(key);
value.appendChild(valueText);
tr.appendChild(value);
tbody.appendChild(tr);
}
}
ajaxResponse.appendChild(tbody);
$("#ajaxResponse").append(ajaxResponse);
}
else alert("No data returned!");
}
});
});

Categories

Resources