How to refresh the ViewBag? - javascript

I want to send either a 1 (New Code) or 0 (no New Code), but still the ViewBag only accepts the first value that is written to it.
Controller
int timesRun = 0;
int newID;
private ApplicationDbContext Context = new ApplicationDbContext();
[HttpGet]
public IActionResult StartPage(string Code)
{
Debug.WriteLine("Start: " + Code);
//Select BauTeilId
var list = (from t in Context.Result select new { t.BauTeilId }).ToList();
//Checking if already exists
for (int i = 0; i < list.Count; i++)
{
if (Code != null)
{
if (list[i].BauTeilId.Equals(Code))
{
newID = 0;
Debug.WriteLine("Keine neue ID " + newID);
}
else
{
newID = 1;
Debug.WriteLine("Neue ID " + newID);
break;
}
Debug.WriteLine(list[i].BauTeilId);
}
}
ViewBag.newID = newID;
return View();
}
HTML
#{
ViewData["Title"] = "Home Page";
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Starter</title>
<style>
p {
margin-top: 30%;
margin-left: 20%;
margin-right: 20%;
font-family: Arial;
font-size: 25px;
text-align: center;
}
#Code {
border: 2px solid black;
}
</style>
</head>
<body>
<h1>Example Code: 249765876358312345655</h1>
<p>
Eingabe des Maschinen Codes:
<br />
<input id="Code"
name="Code"
pattern=""
size="30"
spellcheck="false"
title="Maschine Code"
value="">
</p>
#{
var data = ViewBag.newID;
if(data != null)
{
data = ViewBag.newID.ToString().ToLower();
}
}
<script>
var x = document.getElementById("Code");
x.addEventListener('input', function (event) {
//Getting the regex sorted out
x = document.getElementById("Code").value;
let vars = x;
let digits = vars.match(/^\d{13}(\d{6})\d{2}$/)[1];
let stringDigits = digits.toString();
if (stringDigits.length == 6 && vars.length == 21) {
//New ID or not
let newID = '#data'.toString().toLowerCase();
Boolean(newID);
alert(newID);
if (newID === '1') window.location.href = '/home/NewIDSettingsPage';
else if(newID === '0')window.location.href = '/home/Kontrolle';
else alert("ERROR");
//Send to Kontrolle
document.getElementById("Code").innerHTML = "";
localStorage.setItem("Code_Kurz", stringDigits);
localStorage.setItem("Code_Lang", x);
//Send Code to Controller
$.ajax({
url: "#Url.Action("StartPage")",
type: "GET",
data: {Code: stringDigits},
success: function (data) { console.log("Succ: " + data); },
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText;
console.log("ERROR: " + errorMessage);},
});}});
</script>
</body>
</html>
I don't know how to fix that or if there is an other solution to this.
Similar questions:
How To Change or refresh data using ViewBag in MVC3
(That tutorial didnt help me either)

Let assume your list contains 2 rows and during for iteration first time this if (list[i].BauTeilId.Equals(Code)) condition returns true and second time return false.
Your loop will set newID value based on last iteration. In last iteration if if (list[i].BauTeilId.Equals(Code)) return 0 else 1.
Check out below updated code :
if (Code != null)
{
if count > 0 will return 0 else return 1
if (list.Where(x => x.BauTeilId.Equals(Code)).Count() > 0)
{
newID = 0;
Debug.WriteLine("Keine neue ID " + newID);
}
else
{
newID = 1;
Debug.WriteLine("Neue ID " + newID);
}
}
//pass value in viewbag
ViewBag.newID = newID;

Related

JS webView Xamarinforms

I have been trying to call action from JS code in Xamarin forms on iOS. once I click on the code js is not called. this is an example I have been testing. Once I click the text gets highlighted but the function is not triggered, I don't want to display the action after clicking the button but I after I click the text. Please can you tell me what am I doing wrong.
<StackLayout x:Name="slHybridView" >
</StackLayout>
public MainPage()
{
InitializeComponent();
BindingContext = new LearningPageViewModel();
((LearningPageViewModel)BindingContext).TextChanged += TextChanged;
hybridWebView = new HybridWebView()
{
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
Content = ((LearningPageViewModel)BindingContext).ArticleHtmlFormat,
};
hybridWebView.RegisterAction(data => DisplayAlert("Alert", "Hello " + data, "OK"));
slHybridView.Children.Clear();
slHybridView.Children.Add(hybridWebView);
}
public class HybridWebViewRenderer : WkWebViewRenderer, IWKScriptMessageHandler
{
const string JavaScriptFunction = "function invokeCSharpAction(data){window.webkit.messageHandlers.invokeAction.postMessage(data);}";
WKUserContentController userController;
public HybridWebViewRenderer()
{
}
public HybridWebViewRenderer(WKWebViewConfiguration config) : base(config)
{
userController = config.UserContentController;
var script = new WKUserScript(new NSString(JavaScriptFunction), WKUserScriptInjectionTime.AtDocumentEnd, false);
userController.AddUserScript(script);
userController.AddScriptMessageHandler(this, "invokeAction");
}
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
userController.RemoveAllUserScripts();
userController.RemoveScriptMessageHandler("invokeAction");
HybridWebView hybridWebView = e.OldElement as HybridWebView;
hybridWebView.Cleanup();
}
if (e.NewElement != null)
{
var html = string.Empty;
var iOSHtmlWithScaling = html.Insert(0, "<meta name='viewport' content='width=device-width,initial-scale=1,maximum-scale=1' />");
var script = new WKUserScript(new NSString(JavaScriptFunction), WKUserScriptInjectionTime.AtDocumentEnd, false);
Configuration.UserContentController.AddUserScript(script);
Configuration.UserContentController.AddScriptMessageHandler(this, JavaScriptFunction);
LoadData(((HybridWebView)Element).Content, iOSHtmlWithScaling, "utf-8", new NSUrl(""));
}
}
public void DidReceiveScriptMessage(WKUserContentController userContentController, WKScriptMessage message)
{
((HybridWebView)Element).InvokeAction(message.Body.ToString());
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
((HybridWebView)Element).Cleanup();
}
base.Dispose(disposing);
}
}
public LearningPageViewModel()
{
articleHtmlFormat = ArticleHtml();
}
public string ArticleHtml()
{
var articleHtml = #"<html>
<head>
<meta name='viewport' content='width=device-width,initial-scale=1,maximum-scale=1' />
</head>
<body class='avat'>
<style>
.avat {
font-family: sans-serif;
font-size: 15px;
text-align: justify;
}
.title {
font-size: 16px;
}
.red {
color: red;
}
.word {
font-weight: bold;
}
.phrase {
text-decoration: underline;
}
</style>
<script type='text/javascript'>
function invokeCSCode(data) {
var els = document.getElementsByClassName('red');
while (els[0]) {
els[0].classList.remove('red');
}
invokeCSharpAction(data);
var my_element = document.querySelector('[sentenceId=' + data + ']');
my_element.scrollIntoView({
behavior: 'smooth',
block: 'center',
inline: 'nearest'
});
var sentenceName = my_element.getAttribute('sentenceName');
if (data[0] === 's')
{
var x = document.querySelectorAll('[sentenceName=' + sentenceName + ']');
var i;
for (i = 0; i < x.length; i++)
{
x[i].classList.add('red');
}
}
else
{
my_element.classList.add('red');
}
}
function scrollToPosition(data) {
var els = document.getElementsByClassName('red');
while (els[0]) {
els[0].classList.remove('red');
}
var my_element = document.querySelector('[sentenceId=' + data + ']');
my_element.scrollIntoView({
behavior: 'smooth',
block: 'center',
inline: 'nearest'
});
var sentenceName = my_element.getAttribute('sentenceName');
if (data[0] === 's')
{
var x = document.querySelectorAll('[sentenceName=' + sentenceName + ']');
var i;
for (i = 0; i < x.length; i++)
{
x[i].classList.add('red');
}
}
else
{
my_element.classList.add('red');
}
}
</script>
";
var spans = FindAllClickableSpans(Article()).ToArray();
for (int i = 0; i < spans.Length; i++)
{
articleHtml += "<span ";
articleHtml += " sentenceId='" + i + "' onclick='javascript: invokeCSCode(\"" + i + "\");' sentenceName='" + i + "'>" + spans[i] + "</span>";
}
articleHtmlFormat = articleHtml;
return articleHtmlFormat;
}
public string Article()
{
return #"Excuse me,” said a girl, “you look lost. Can I help you?”\“Yes, please. Thank you.";
}
private IEnumerable<string> FindAllClickableSpans(string article)
{
article = article.ToLower();
return article.Split('.');
}

Socket.io emit events not updating the client side until the io.on('connection) functions reaches the end

I am making a blockchain in Node.js and updating the client side with socket.io. I want to add a new block to a list on the client side everytime a new block is generated, but they all get added together at the end when generating is finished. I have an emit event fire everytime after a new block is generated ( inside of a for loop ), so I don't know why the client side only updates when all of the blocks are generated.So basically they all get added at the same time instead of one by one. Any help is greatly appreciated!
client.js
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const myArgs = process.argv.slice(2);
const port = myArgs[0];
const SHA256 = require("crypto-js/sha256");
var indexNumber = 1;
var difficulity = 4;
var Nonce = 0;
const data = "This is block ";
class Block {
constructor(index, timestamp, data, previousHash, diff, nonce) {
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.previousHash = previousHash;
this.diff = diff;
this.nonce = nonce;
this.hash = this.generateHash();
}
generateHash() {
var good;
var failed = 0;
while (true) {
good = false;
var newHash = SHA256(this.index + this.timestamp + this.previousHash + JSON.stringify(this.data) + this.diff + this.nonce).toString();
for (var i = 0; i < this.diff; i++) {
if (newHash[i] == '0')
good = true;
else {
good = false;
break;
}
}
if (good) {
io.emit('goodHash', (newHash + " Difficulity: " + this.diff));
break;
}
else {
this.nonce++;
if (failed == 30000) {
io.emit('wrongHash', (newHash + " Difficulity: " + this.diff));
failed = 0;
}
else
failed++
}
}
return newHash;
}
}
class Blockchain {
constructor() {
this.blockchain = [this.createGenesisBlock()];
}
createGenesisBlock() {
var tmp = new Block(0, Date.now(), "Genesis block", "0", difficulity, Nonce);
io.emit('newBlock', JSON.stringify(tmp));
console.log(tmp);
return tmp;
}
getTheLatestBlock() {
return this.blockchain[this.blockchain.length - 1];
}
addNewBlock(newBlock) {
this.blockchain.push(newBlock);
}
validateBlock(newBlock) {
const latestBlock = this.getTheLatestBlock();
if (newBlock.previousHash !== latestBlock.hash)
return false;
if (newBlock.index <= latestBlock.index)
return false;
if (newBlock.hash !== SHA256(newBlock.index + newBlock.timestamp + newBlock.previousHash + JSON.stringify(newBlock.data) + newBlock.diff + newBlock.nonce).toString())
return false;
return true;
}
validateChain() {
for (let i = 1; i < this.blockchain.length; i++) {
const currentBlock = this.blockchain[i];
const previousBlock = this.blockchain[i - 1];
if (currentBlock.hash !== SHA256(currentBlock.index + currentBlock.timestamp + currentBlock.previousHash + JSON.stringify(currentBlock.data) + currentBlock.diff + currentBlock.nonce).toString()) {
return false;
}
if (currentBlock.previousHash !== previousBlock.hash) {
return false;
}
if (currentBlock.index <= previousBlock.index)
return false;
return true;
}
}
}
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
socket.on('set transports',() =>{
socket.transports = ["websocket"];
});
console.log('GUI connected on port: ' + port);
io.emit('onConnection', port);
socket.on('mine', function () {
console.log("mining in progress...");
let logCoin = new Blockchain();
for (var i = 0; i < 5; i++) {
while (true) {
var tmp = new Block(indexNumber, Date.now(), data + indexNumber, logCoin.getTheLatestBlock().hash, difficulity, Nonce);
if (logCoin.validateBlock(tmp)) {
io.emit('newBlock', JSON.stringify(tmp));
console.log(tmp);
logCoin.addNewBlock(tmp);
indexNumber++;
break;
}
}
}
//console.log(logCoin);
//io.emit('blockLedger', JSON.stringify(logCoin, null));
})
socket.on('disconnect', () => {
console.log("Client has disconnected");
indexNumber = 1;
});
});
server.listen(port, () => {
console.log('listening on port ' + port + ':');
});
index.html
<!DOCTYPE html>
<html>
<style>
body {
margin: 10px;
padding-bottom: 3rem;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
#header {
display: flex;
flex-direction: row;
}
#contentWrap {
display: flex;
margin-top: 10px;
height: 100%;
}
#contentWrap>div {
flex: 1;
border: 1px solid black;
overflow-y: scroll;
overflow-x: visible;
height: 100vh;
}
#blocks {
list-style-type: none;
margin: 0;
padding: 0;
}
#blocks>li {
padding: 0.5rem 1rem;
white-space: pre-wrap;
overflow-wrap: break-word;
}
#minedBlocks {
list-style-type: none;
margin: 0;
padding: 0;
}
#minedBlocks>li {
padding: 0.5rem 1rem;
white-space: pre-wrap;
overflow-wrap: break-word;
}
#port {
position: absolute;
right: 10px;
}
</style>
<body>
<div id="header">
<div id="element1">
<h1>Blockchain</h1>
<p id="connectionStatus">Status: Offline</p>
<form id="form" action="">
<button id="mine">Mine</button>
</form>
</div>
<div id="element2" style="align-self: center;">
<form id="form" action="">
<div id="port">
<input id="portInput" autocomplete="off" /><button>Connect port</button>
</div>
</form>
</div>
</div>
<div id="contentWrap">
<div id="ledger">
<ul id="blocks">
<li>Blockchain ledger</li>
</ul>
</div>
<div id="mined">
<ul id="minedBlocks">
<li>Mining...</li>
</ul>
</div>
</div>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
var mine = document.getElementById('mine');
function padTo2Digits(num) {
return num.toString().padStart(2, '0');
};
function formatDate(date) {
return (
[
padTo2Digits(date.getDate()),
padTo2Digits(date.getMonth() + 1),
date.getFullYear(),
].join('.') +
' ' +
[
padTo2Digits(date.getHours()),
padTo2Digits(date.getMinutes()),
padTo2Digits(date.getSeconds()),
].join(':')
);
};
function printBlock(block, parent, div) {
var formattedDate;
var timeStamp;
let item = document.createElement("li");
item.style.color = "green";
item.textContent = "Index: " + block.index + "\r\n";
item.textContent += "Data: " + block.data + "\r\n";
timeStamp = new Date(block.timestamp);
formattedDate = formatDate(timeStamp);
item.textContent += "Timestamp: " + formattedDate + "\r\n";
item.textContent += "PreviousHash: " + block.previousHash + "\r\n";
item.textContent += "Difficulity: " + block.diff + "\r\n";
item.textContent += "Nonce: " + block.nonce + "\r\n";
item.textContent += "Hash: " + block.hash + "\r\n";
parent.appendChild(item);
div.scrollTop = ledger.scrollHeight;
}
socket.on('onConnection', function (msg) {
document.getElementById('connectionStatus').innerText = "Status: Online: PORT " + msg;
});
socket.on('blockLedger', function (msg) {
var blocks = document.getElementById('blocks');
var obj = JSON.parse(msg);
var ledger = document.getElementById('ledger');
obj.blockchain.forEach(function (arrayItem) {
printBlock(arrayItem, blocks, ledger);
});
});
socket.on('wrongHash', function (msg) {
var minedBlocks = document.getElementById('minedBlocks');
var mined = document.getElementById('mined');
let item = document.createElement("li");
item.style.color = 'red';
item.textContent = msg;
minedBlocks.appendChild(item);
mined.scrollTop = mined.scrollHeight;
});
socket.on('goodHash', function (msg) {
var minedBlocks = document.getElementById('minedBlocks');
var mined = document.getElementById('mined');
let item = document.createElement("li");
item.style.color = 'green';
item.textContent = msg;
minedBlocks.appendChild(item);
mined.scrollTop = mined.scrollHeight;
});
socket.on('newBlock', function (msg) {
var blocks = document.getElementById('blocks');
var obj = JSON.parse(msg);
var ledger = document.getElementById('ledger');
printBlock(obj, blocks, ledger);
});
mine.addEventListener('click', function (e) {
e.preventDefault();
socket.emit('mine');
});
</script>
</body>
</html>
Edit
I am still trying to find a solution. I tried changing the socket io transport options in both the .js file and index.html, flushing the buffer and using volatile.emit but nothing worked. I think for some reason the emits get buffered and then sent at the end, but i dont know why.
Also, the first two emits execute well (so the 'onConnection' is first and either the 'wrongHash' or 'goodHash' second), but everything after that is sent (or received) after the for loop is executed.
You should call your emit function on
for (var i = 0; i < 5; i++) {
while (true) {
var tmp = new Block(indexNumber, Date.now(), data + indexNumber, logCoin.getTheLatestBlock().hash, difficulity, Nonce);
if (logCoin.validateBlock(tmp)) {
//here you should write this
io.emit('newBlock', JSON.stringify(tmp)); //this is where the new block is emmited
logCoin.addNewBlock(tmp);
indexNumber++;
break;
}
}
//not here
io.emit('newBlock', JSON.stringify(tmp)); //this is where the new block is emmited
console.log(tmp);
}

How to access values of Input in a List

For my Project I need to have a site, which can generate a custom amount of Inputs, which will become buttons in another page.
And I need the values for the Input in order to Label the Buttons correctly.
HTML
<h2>settings:</h2>
<p>Add Amount of Checks:</p>
<input id="NumOfButtons"
name="NumOfButtons"
pattern=""
size="30"
spellcheck="false"
title="Amount of Checks"
value="">
<script>
let input = document.getElementById("NumOfButtons");
let listTA = new Array;
input.addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
event.preventDefault();
var x = parseInt(document.getElementById("NumOfButtons").value);
listTA = new Array(x);
for (let i = 0; i < x; ++i) {
var textarea = document.createElement("input");
textarea.name = "input";
textarea.maxLength = "100";
textarea.id = "TextAreaID"
listTA[i] = textarea;
document.getElementById("Buttons").appendChild(textarea);
}
}
});
</script>
<div id="Buttons">
<br />
<button onclick="sendDataAndGoToKontrolle()">save & continue</button>
<p>Reset F5</p>
</div>
<script>
function sendDataAndGoToKontrolle() {
var filtered;
if (listTA != null) {
let x = new Array;
for (let i = 0; i < listTA.length; ++i) x[i] = listTA[i].document.getElementById("TextAreaID").value;
if (!(x.length === 0)) {
for (let i = 0; i < x.length; ++i) {
if (x[i] === null) {
var filtered = x.filter(function (el) { return el != null; });
console.log("TextAreas filtered!")
} else console.log("Nothing to filter!")
}
} else console.log("Nothin written in TextAreas!");
} else console.log("No TextArea created!");
if (!(filtered === null)) {
//Send Prüfungen to Controller
$.ajax({
url: "#Url.Action("NewIDSettingsPage")",
type: "GET",
data: { Prüfungen: filtered },
success: function () {
console.log("Successfully sent!");
//window.location.href = '/home/NewIDSettingsPage';
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText;
console.log("ERROR: " + errorMessage);}});
} else console.log("ERROR");
}
</script>
The result should be a list/Array of string(values of the Inputs).
If you need any further information, please write a Comment and I will look to reply quickly.
Do not give all the input elements the same id. textarea.id = "TextAreaID" is wrong.
If you want to group the inputs together you should set the class:
textarea.className = "TextAreaClass"
Or if you want to give each one an id, append i to the id to make it unique:
textarea.id = "TextAreaID"+i;
When trying to get the values of your inputs you have the following:
x[i] = listTA[i].document.getElementById("TextAreaID").value;
Which doesn't make a lot of sense. What you should probably be doing is:
x[i] = listTA[i].value;
Because you have stored the element in the array, you don't need to get the element from the document.

How to use knockoutJS when converting XML to CSV?

I have created a application where I want to convert XML file into CSV format on the screen. I have done it through JavaScript but I want to use KnockoutJS for the same. I am newbie to Knockout so do not have enough ideas for implementing the same.
Can anyone please suggest me how to use knockout here?
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js'></script>
<script type='text/javascript' src="https://cdn.rawgit.com/abdmob/x2js/master/xml2json.js"></script>
<script>
function xmlTocsv() {
debugger;
var data = $("#xmlArea").val();
var xml = "";
if (data !== null && data.trim().length !== 0) {
debugger;
try {
xml = $.parseXML(data);
} catch (e) {
throw e;
}
var x2js = new X2JS();
data = x2js.xml2json(xml);
jsonTocsvbyjson(data);
}
}
function jsonTocsvbyjson(data, returnFlag) {
debugger;
arr = [];
flag = true;
var header = "";
var content = "";
var headFlag = true;
try {
var type1 = typeof data;
if (type1 != "object") {
data = processJSON($.parseJSON(data));
} else {
data = processJSON(data);
}
} catch (e) {
if (returnFlag === undefined || !returnFlag) {
console.error("Error in Convert to CSV");
} else {
console.error("Error in Convert :" + e);
}
return false;
}
$.each(data, function(k, value) {
if (k % 2 === 0) {
if (headFlag) {
if (value != "end") {
header += value + ",";
} else {
// remove last colon from string
header = header.substring(0, header.length - 1);
headFlag = false;
}
}
} else {
if (value != "end") {
var temp = data[k - 1];
if (header.search(temp) != -1) {
content += value + ",";
}
} else {
// remove last colon from string
content = content.substring(0, content.length - 1);
content += "\n";
}
}
});
if (returnFlag === undefined || !returnFlag) {
$("#csvArea").val(header + "\n" + content);
} else {
return (header + "\n" + content);
}
}
function processJSON(data) {
debugger;
$.each(data, function(k, data1) {
var type1 = typeof data1;
if (type1 == "object") {
flag = false;
processJSON(data1);
arr.push("end");
arr.push("end");
} else {
arr.push(k, data1);
}
});
return arr;
}
</script>
</head>
<body>
<h1>XML2CSV Demo</h1>
<button id="convertToXmlBtn" onclick="xmlTocsv()">XML => CSV</button>
<div>
<h4>XML:</h4>
<textarea id="xmlArea" cols="55" rows="15"></textarea>
</div>
<div>
<h4>CSV:</h4>
<textarea id="csvArea" cols="55" rows="15"></textarea>
</div>
</body>
</html>
There really isn't much Knockout to add to your code. I've used a click binding and a value binding for 2 observables I created - xmlArea and csvArea. This eliminates the need for you to use id attributes and jQuery's val() function.
I've also moved the entire code to the bottom of the body tag, otherwise Knockout will not bind with the HTML.
The rest of your code is untouched.
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js'></script>
<script type='text/javascript' src="https://cdn.rawgit.com/abdmob/x2js/master/xml2json.js"></script>
</head>
<body>
<h1>XML2CSV Demo</h1>
<button id="convertToXmlBtn" data-bind="click: xmlTocsv">XML => CSV</button>
<div>
<h4>XML:</h4>
<textarea cols="55" rows="15" data-bind="value: xmlArea"></textarea>
</div>
<div>
<h4>CSV:</h4>
<textarea cols="55" rows="15" data-bind="value: csvArea"></textarea>
</div>
</body>
<script>
var viewmodel = function(){
var self = this;
self.xmlArea = ko.observable();
self.csvArea = ko.observable();
self.xmlTocsv = function() {
debugger;
var data = self.xmlArea();
var xml = "";
if (data !== null && data.trim().length !== 0) {
debugger;
try {
xml = $.parseXML(data);
} catch (e) {
throw e;
}
var x2js = new X2JS();
data = x2js.xml2json(xml);
jsonTocsvbyjson(data);
}
}
function jsonTocsvbyjson(data, returnFlag) {
debugger;
arr = [];
flag = true;
var header = "";
var content = "";
var headFlag = true;
try {
var type1 = typeof data;
if (type1 != "object") {
data = processJSON($.parseJSON(data));
} else {
data = processJSON(data);
}
} catch (e) {
if (returnFlag === undefined || !returnFlag) {
console.error("Error in Convert to CSV");
} else {
console.error("Error in Convert :" + e);
}
return false;
}
$.each(data, function(k, value) {
if (k % 2 === 0) {
if (headFlag) {
if (value != "end") {
header += value + ",";
} else {
// remove last colon from string
header = header.substring(0, header.length - 1);
headFlag = false;
}
}
} else {
if (value != "end") {
var temp = data[k - 1];
if (header.search(temp) != -1) {
content += value + ",";
}
} else {
// remove last colon from string
content = content.substring(0, content.length - 1);
content += "\n";
}
}
});
if (returnFlag === undefined || !returnFlag) {
self.csvArea(header + "\n" + content);
} else {
return (header + "\n" + content);
}
}
function processJSON(data) {
debugger;
$.each(data, function(k, data1) {
var type1 = typeof data1;
if (type1 == "object") {
flag = false;
processJSON(data1);
arr.push("end");
arr.push("end");
} else {
arr.push(k, data1);
}
});
return arr;
}
};
ko.applyBindings(new viewmodel());
</script>
</html>

Ajax Cascade Dropdownlist

I am trying to create cascade dropdownlist using ajax. So when user selects the degree dropdown, the second dropdown box displays schools that offer that selected degree. But for some reasons, my ajax $("#degreeid").on("change",function(){}); does not get called. Not sure why. Help please!
Index.cshtml
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div id="select-degree-form">
<div">
<span id="Label1">Degree List</span> #Html.DropDownList("degreeid", (IEnumerable<SelectListItem>)ViewBag.DegreeList, "Select a Degree")
</div>
</div>
<div id="select-school-form">
<div">
<span id="Label1">School List</span><select id="SecondDropdown"></select>
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script>
$("#degreeid").on("change", function () {
showValue($(this).val());
});
function showValue(val) {
console.log(val);
$.getJSON('#Url.Action("GetDropdownList", "Home")' + "?value=" + val, function (result) {
$("#SecondDropdown").html(""); // makes select null before filling process
var data = result.data;
for (var i = 0; i < data.length; i++) {
$("#schoollist").append("<option>" + data[i] + "</option>")
}
})
}
</script>
</div>
<!-- MORE CODE -->
HomeController.cs
[HttpGet]
public JsonResult GetDropdownList(int? value)
{
using (DataModel db = new DataModel())
{
var qry = (from a in db.schools where a.degree_id == value && a.active == true
select new
{
institution_id = a.institution_id,
institution_name = b.institution_name
}).Distinct();
List<string> institutionList = new List<string>();
foreach(var item in qry)
{
institutionList.Add(item.institution_name);
}
return Json(new { data = institutionList }, JsonRequestBehavior.AllowGet);
}
}
Try adding your script to on ready function:
change this:
$("#degreeid").on("change", function () {
showValue($(this).val());
});
For this:
$(function(){
$("#degreeid").on("change", function () {
showValue($(this).val());
});
});
And change this:
function showValue(val) {
console.log(val);
$.getJSON('#Url.Action("GetDropdownList", "Home")' + "?value=" + val, function (result) {
$("#SecondDropdown").html(""); // makes select null before filling process
var data = result.data;
for (var i = 0; i < data.length; i++) {
$("#schoollist").append("<option>" + data[i] + "</option>")
}
})
}
For this:
function showValue(val) {
console.log(val);
$.getJSON('#Url.Action("GetDropdownList", "Home")' + "?value=" + val, function (result) {
$("#SecondDropdown").html(""); // makes select null before filling process
var data = result.data;
for (var i = 0; i < data.length; i++) {
$("#schoollist").append("<option value=" + data[i]["institution_id"] + ">" + data[i]["institution_name"] + "</option>")
}
})
}

Categories

Resources