insert razor code in ajax - javascript

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 ")

Related

API Call in for loop

I'm working on using Twitch's API (from an alternate link because of CORS). The html comes back empty when this is ran. Is it because of the callback and what can I do to get the data? I can confirm that the link works and have tried stepping through it with no luck.
let usernames = ['freecodecamp'];
let api = '';
let html = '';
for(let i = 0; i < usernames.length; i++) {
api = 'https://wind-bow.gomix.me/twitch-api/streams/' + usernames[i] + '?callback=?';
$.getJSON(api, function(data) {
let online = data.stream == null;
if(online) {
html += usernames[i] + '\nStatus: Offline';
}
else {
html += usernames[i] + '\nStatus: Online';
}
});
}
if(html != '') {
$('#data_display').html('<h1>' + html + '</h1>');
}
Put your last append html block inside the getJSON :
$.getJSON(api, function(data) {
let online = data.stream == null;
if(online) {
html = usernames[i] + '\nStatus: Offline';
}
else {
html = usernames[i] + '\nStatus: Online';
}
$('#data_display').append('<h1>' + html + '</h1>');
});
And also use .append instead of .html , otherwise it will replace the html inside of #data_display.
There is no need to do html += ....
I think javascript promise will help with your situation, take jQuery deferred API as an example:
function fetchUserStatus(username) {
var defer = jQuery.Deferred();
var api = 'https://wind-bow.gomix.me/twitch-api/streams/' + username + '?callback=?';
$.getJSON(api, function(data) {
let online = data.stream == null;
if (online) {
defer.resolve('Offline');
} else {
defer.resolve('Online');
}
});
return defer.promise();
}
let usernames = ['freecodecamp'];
let promises = [];
for (let i = 0; i < usernames.length; i++) {
promises.push(fetchUserStatus(usernames[i]));
}
$.when.apply($, promises).then(function() {
let html = '';
for (let i = 0; i < arguments.length; i++) {
html += usernames[i] + '\nStatus: ' + arguments[i];
}
$('#data_display').append('<h1>' + html + '</h1>');
});
The jQuery when does not support passing an array of promises, that's why the apply function is used, and at the then callback, you'll need to use the arguments to refer to all the resolved value from the promises.
Wish this will help.

Encrypt & decrypt URL parameters in spring

I would like to encrypt URL GET parameters that all links will be something like below.
Encrypted in html:
home.htm?ecryptParam=aajsbjabsjvyhasyayasy
Actual:
home.htm?fName=samir&lName=vora
At the same time, in controller class it will have the decrypted value automatically and I can retrieve it from request. e.g.:
Link:
home.htm?ecrypt=SKJIIU86iuGkJGkJFHGBVBVn
Controller class:
request.getParameter("fName"); will return samir
Samir, If you passing value as encrypt format in url and you will retrieve using request param as encrypt format, and you will need to decrypt those values for that please refer this link "http://www.code2learn.com/2011/06/encryption-and-decryption-of-data-using.html". It might help.
While you really should handle security backend, simple text obfuscation can be easily achived in JavaScript.
Here is an example:
//Encrypter class
var stringEncrypter = (function() {
function stringEncrypter() {}
stringEncrypter.encrypt = function(str) {
str = str.toString();
var returnCode = [];
for (var strIndex = 0; strIndex < str.length; strIndex++) {
var element = str[strIndex];
//Push with bitwise offset (or remove the bitwise offset here and in decrypt)
returnCode.push(element.charCodeAt(0) << this.off);
}
//return a joined string
return returnCode.join(this.splitter);
};
stringEncrypter.decrypt = function(str) {
var list = str.split(this.splitter);
var returnCode = "";
for (var strIndex = 0; strIndex < list.length; strIndex++) {
var element = list[strIndex];
//Push with bitwise offset (or remove the bitwise offset here and in encrypt)
returnCode += String.fromCharCode(parseInt(element) >> this.off);
}
return returnCode;
};
stringEncrypter.encryptUrl = function(url) {
if (url.substr(url.indexOf("?") >= 0)) {
var str = url.substr(url.indexOf("?") + 1);
if (str.lastIndexOf("#") >= 0) {
str = str.substr(0, str.lastIndexOf("#"));
}
var params = str.split("&");
for (var paramIndex = 0; paramIndex < params.length; paramIndex++) {
var param = params[paramIndex].split("=");
param[0] = this.encrypt(param[0]);
param[1] = this.encrypt(param[1]);
params[paramIndex] = param.join("=");
}
url = url.substr(0, url.indexOf("?") + 1) + params.join("&") +
(url.lastIndexOf("#") >= 0 ? url.substr(url.lastIndexOf("#")) : "");
}
return url;
};
stringEncrypter.decryptUrl = function(url) {
if (url.substr(url.indexOf("?") >= 0)) {
var str = url.substr(url.indexOf("?") + 1);
if (str.lastIndexOf("#") >= 0) {
str = str.substr(0, str.lastIndexOf("#"));
}
var params = str.split("&");
for (var paramIndex = 0; paramIndex < params.length; paramIndex++) {
var param = params[paramIndex].split("=");
param[0] = this.decrypt(param[0]);
param[1] = this.decrypt(param[1]);
params[paramIndex] = param.join("=");
}
url = url.substr(0, url.indexOf("?") + 1) + params.join("&") +
(url.lastIndexOf("#") >= 0 ? url.substr(url.lastIndexOf("#")) : "");
}
return url;
};
return stringEncrypter;
}());
//Bitwise offset. Completely optional
stringEncrypter.off = 2;
stringEncrypter.splitter = "|";
//Encrypt a string
console.log(stringEncrypter.encrypt("Testing123"));
//Decrypt a string
console.log(stringEncrypter.decrypt(stringEncrypter.encrypt("Testing123")));
//Decrypt a url
console.log(stringEncrypter.encryptUrl("www.test.dk?test=45"));
//Encrypt a url
console.log(stringEncrypter.decryptUrl(stringEncrypter.encryptUrl("www.test.dk?test=45")));
//Decrypt a url with #
console.log(stringEncrypter.encryptUrl("www.test.dk?test=45#title1"));
//Encrypt a url with #
console.log(stringEncrypter.decryptUrl(stringEncrypter.encryptUrl("www.test.dk?test=45#title1")));

Sending Array with Jquery

$('[data-toggle="mftapproveCheck"]').click(function () {
var selected = $("#checkboxes input:checked").map(function (i, el) { return el.value; }).get();
//alert("selected = [" + selected + "]\nas int = \"" + selected.join(";") + "\"");
var url = $(this).data("url") + "/" + selected;
var title = $(this).data("title");
callback: function (result) {
if (result) {
$("#preLoader").fadeIn('fast');
$.post(url, function (json) {
if (json.IsComplete) {
$("#" + id).remove();
BSToastr.show("success", "Başarılı", "İşleminiz Başarıyla Gerçekleştirildi.");
}
else {
BSToastr.show("error", "Hata", "İşleminiz Gerçekleştirilemedi.");
}
$("#preLoader").fadeOut('fast');
});
}
}
});
});
Here I am trying to send selected to controller. this works when only 1 Id comes but doesnt work when several comes. but alert always working. How can I send Array from here ?
public ActionResult ApproveSelected(int[] selected)
{
var itema = selected;
var itemb = itema;
try
{
var AllParticipants = Db.Participants
.Where(m => selected.Contains(m.Id))
.OrderBy(m => m.Id)
.ToList();
for (int i = 0; i < AllParticipants.Count; i++)
{
var item = AllParticipants.First();
item.Approval = true;
var itemRemove = AllParticipants.First();
AllParticipants.Remove(item);
}
Db.SaveChanges();
}
catch
{
return Json(new { IsComplete = false });
}
return Json(new { IsComplete = true });
}
You're not sending a list because of this line:
var url = $(this).data("url") + "/" + selected;
which just concats selected without actually converting it. If you take a look at your alert, you actually convert it to a string via the join function which is why you see all the items.
selected.join(";"); // <-- used in your alert()
So what I'd suggest is using that same join call when setting your url variable:
var url = $(this).data("url") + "/" + selected.join(";");

post data using ajax and js

Every time i try to use my classes below to post the array i made (also below) the ajax request doesn't pass the input as $_POST values but as $_REQUEST values seen in the web address bar at the top of the screen. I'm very new to Ajax and javascript (only been working with it about a month) so any tips and trick to fix anything below is greatly appreciated.
var formErrors=["Passage","FirstName","Zip"];
var formInput=["EventID","Passage","FirstName","LastName","Email","Organization","Location","Zip"];
Head of HTML
$(function () {
$("#signUp").click(function() {
if(formArrayValidation(formErrors) != false) {
formPostAjax(formInput, 'join-event.php');
}
return false;
});
});
Basics.js
formArrayValidation = function(errorArray) {
for(var i = 0; i < errorArray.length; i++) {
$('.error').hide();
var name = $("input#" + errorArray[i]).val();
if (name == "") {
$("label#" + errorArray[i] + "_error").show();
$("input#" + errorArray[i]).focus();
return false;
}
}
}
formPostAjax = function(inputArray, form) {
var dataString = "";
for(var i = 0; i < inputArray.length; i++)
{
var data = inputArray[i];
var dataInput = $("input#" + data).val();
if(i = 0) {
dataString = dataString + data + '=' + dataInput;
}
else {
dataString = dataString + '&' + data + '=' + dataInput;
}
}
$.ajax ({
type: "POST",
url: form,
data: dataString,
success: function() {
}
});
}
Your event listener should be on the form and it should be:
$('#form_identifier').submit(...);
Additionally, jQuery provides a nice shortcut method for serializing form data:
$('#form_identifier').submit(function(){
var post_data = $(this).serialize()
// ....
return false;
});

Trying to sort repeater rows with this jQuery

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

Categories

Resources