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>")
}
})
}
Related
I am developing a web application which tries to upload a file to a server.
I attempted to create a new ViewModel object, but it still says
undefined
This is my ojprogresslist.js:
"use strict";
define(['ojs/ojcore', 'jquery', 'knockout', 'ojs/ojcomposite','resources/components/file-upload-custom/viewModel.js', 'ojs/ojknockouttemplateutils','ojs/ojcomponentcore', 'ojs/ojlistview', 'ojs/ojprogress'],
function(oj, $, ko, Composite, viewModel, KnockoutTemplateUtils)
{
var deleteButton=
" <oj-button id='btn1' chroming='half' display='icons' on-oj-action='[[deleteItem]]'>"+
" <span class='oj-component-icon oj-panel-remove-icon'></span>"+
"</oj-button>";
var progressItemView =
" <div class='oj-flex oj-sm-justify-content-space-between'>" +
" <div class='oj-flex-item oj-flex oj-sm-flex-direction-column'>" +
" <span data-bind='text: $properties.data.name' class='oj-progresslist-name'></span>" +
" <div data-bind='text: message' class='oj-progresslist-error-message'></div>" +
' </div>' +
" <div class='oj-flex oj-sm-align-items-center'>" +
" <oj-bind-slot name='itemInfo'>" +
" <div class='oj-flex-item oj-flex oj-progresslist-info'>" +
" <span data-bind='text: $data.getSizeInBKMGT($properties.data.size)'></span>" +
' </div>' +
' </oj-bind-slot>' +
" <div class='oj-flex-item oj-flex'>" +
" <oj-progress-status status='{{status}}'" +
" progress='{{progress}}'>" +
' </oj-progress-status>' +
' </div>' +
' </div>' +
deleteButton +
' </div>';
function progressItemViewModel(context) {
var self = this;
this.deleteItem=function(event){
viewModel.deleteList(); // this is undefined
};
};
This is my fileCustom.js:
define([
'knockout',
'ojs/ojcore',
'jquery', 'ojs/ojarraydataprovider', 'fileUploadTransport/MockTransport', 'fileUploadTransport/MockUploadXhr',
'fileUploadTransport/MockTransportItem', 'ojs/ojknockout', 'ojs/ojtoolbar', 'ojs/ojbutton', 'ojs/ojfilepicker', 'resources/js/ojprogresslist'],
function (ko, oj, $, ArrayDataProvider, Transport, MockUploadXhr) {
'use strict';
function ComponentModel(context) {
var self = this;
self.noData = ko.observable(true);
self.isSimulateError = ko.observableArray([]);
self.koArray = ko.observableArray([]);
//create file upload data provider
self.dataProvider = new ArrayDataProvider(self.koArray, {keyAttributes: 'item'});
//add or remove files
self.dataProvider.addEventListener('mutate', function(event) {
if (event.detail.add != null) {
self.noData(false); // enable clear button
}
else if (event.detail.remove != null) {
self.dataProvider.getTotalSize().then(function(size) {
if (size == 0) {
self.noData(true); //disable clear button
}
});
}
});
var options = {
maxChunkSize: 3000000, //for chunkupload
xhr: MockUploadXhr
};
var transport = new Transport(options);
self.status = 200;
function getStatus() {
if (self.isSimulateError().length) {
self.status = (self.status !== 401) ? 401 : 405;
}
else {
self.status = 200;
}
return self.status;
};
//add a filesAdd listener for upload files
self.selectListener = function(event) {
var files = event.detail.files;
if (files.length > 0) {
var fileItems = transport.queue(files);
//add the new files at the beginning of the list
for (var i = 0; i < fileItems.length; i++)
{
self.koArray.unshift(fileItems[i]);
}
//simulate error status
transport.setErrorStatus(getStatus());
//upload files
transport.flush();
}
};
//clear file items from the data provider
self.filterRemove = function(statusList) {
var dataProvider = self.dataProvider;
//remove all data rows
if (! statusList || statusList.length == 0) {
return self.koArray.removeAll();
}
var statuses = {};
for (var i = 0; i < statusList.length; i++) {
statuses[statusList[i]] = true;
}
//In this demo we only fetch up to 25 data rows,
//however you can fetch any number of rows that is right for your app
var asyncIterable = dataProvider.fetchFirst({size:25})[Symbol.asyncIterator]();
return asyncIterable.next().then(
function (fetchResults) {
var data = fetchResults.value.data;
for (var i = 0; i < data.length; i++) {
var progressItem = data[i];
if (statuses[progressItem.status])
self.koArray.remove(progressItem);
}
})
};
//clear file items from the progress list
self.clearProgressList = function(event) {
console.log("hello world"+event);
self.filterRemove(['loaded', 'errored']);
};
self.deleteList = function() {
console.log("hello world");
self.filterRemove(['loaded', 'errored']);
};
}
return ComponentModel;
});
This is my HTML:
<div style="padding-top:10px"></div>
<label for="progressList">File Upload Status</label>
<div style="padding-top:5px"></div>
<oj-progress-list id="progressList" data="[[dataProvider]]">
</oj-progress-list>
</div>
I am calling viewModel.deleteList(); from the ojprogresslist.js file to filecustom.js. And I need to call the deleteList function to delete items from ArrayDataProvider.
But the error I get is
undefined
Can you please help me?
Looking through the code for the viewModel you are returning the function ComponentModel without ever calling the method (I can't remember off the top of my head if requirejs does this for you). so my guess is that the progressItemViewModel in ojprogresslist.js
should probably look like
function progressItemViewModel(context) {
var self = this;
this.deleteItem=function(event){
//not sure if the context that is passed in to the parent function is what is expected by the ComponentModel.
//so the call may be viewModel().deleteList();
viewModel(context).deleteList();
};
};
The other thing to note is that you are not using context in function ComponentModel(context){...}.
I'm working with a javascript library called slick grid to display a grid on a webpage. I need to send the grid information via ajax to a server. My problem is I need to used jquery notation to access the grid.
Here is the div grid:
<div id="myGrid" style="width:100%;height:300px;"></div>
Here is the javascript I'm using:
var grid;
$(function () {
for (var i = 0; i < 30; i++) {
data[i] = {
pbc_id: "00" + i,
task: "Task " + i,
due_date: "02/02/2017"
};
}
grid = new Slick.Grid("#myGrid", data, columns, options);
grid.setSelectionModel(new Slick.CellSelectionModel());
grid.registerPlugin(new Slick.AutoTooltips());
// set keyboard focus on the grid
grid.getCanvasNode().focus();
var copyManager = new Slick.CellCopyManager();
grid.registerPlugin(copyManager);
copyManager.onPasteCells.subscribe(function (e, args) {
if (args.from.length !== 1 || args.to.length !== 1) {
throw "This implementation only supports single range copy and paste operations";
}
var from = args.from[0];
var to = args.to[0];
var val;
for (var i = 0; i <= from.toRow - from.fromRow; i++) {
for (var j = 0; j <= from.toCell - from.fromCell; j++) {
if (i <= to.toRow - to.fromRow && j <= to.toCell - to.fromCell) {
val = data[from.fromRow + i][columns[from.fromCell + j].field];
data[to.fromRow + i][columns[to.fromCell + j].field] = val;
grid.invalidateRow(to.fromRow + i);
}
}
}
grid.render();
});
grid.onAddNewRow.subscribe(function (e, args) {
var item = args.item;
var column = args.column;
grid.invalidateRow(data.length);
data.push(item);
grid.updateRowCount();
grid.render();
});
})
var DocumentViewModel = function () {
var self = this;
self.sendGridData = function () {
var data = $("myGrid");
//TODO: access the grid data and convert the data to a json string
$.ajax({
async: true,
type: "POST",
dataType: "json",
url: '/MyService/SubmitRequest',
data: ,
success: function (response) {
alert("success");
},
error: function (xhr, textStatus, exceptionThrown) {
alert("error");
}
});
};
};
Any help would be greatly appreciated.
Edit: trying to access the grid variable where my todo is
I managed to recreate your problem above. Had to add some code to get the example to execute as is. It seems your main problem is that though the grid variable is declared in the global address space, iether the contents of DocumentViewModel cannot access it because everything inside DocumentViewModel is private to this function or perhaps your DocumentViewModel is executing before the other code is declared (more likely) however you've not shown how or WHEN you are triggering DocumentViewModel so I can't tell you for sure.
But by moving DocumentViewModel inside '$(function () {' finally the variable was found and the grid was accessible.
I'll paste my code below which includes yours plus the extra I added to get it to execute.
<html>
<head>
<h1>myGrid SO Question Test</h1>
<script src="http://code.jquery.com/jquery-1.7.min.js"></script>
<script src="http://mleibman.github.com/SlickGrid/lib/jquery.event.drag-2.2.js"></script>
<style src="http://mleibman.github.com/SlickGrid/css/smoothness/jquery-ui-1.8.16.custom.css"></style>
<script src="http://mleibman.github.com/SlickGrid/slick.core.js"></script>
<script src="http://mleibman.github.com/SlickGrid/slick.grid.js"></script>
<script src="http://mleibman.github.com/SlickGrid/slick.editors.js"></script>
<script src="http://mleibman.github.com/SlickGrid/slick.formatters.js"></script>
<script src="http://mleibman.github.com/SlickGrid/slick.dataview.js"></script>
<script src="http://mleibman.github.io/SlickGrid/plugins/slick.cellselectionmodel.js"></script>
<script src="http://mleibman.github.io/SlickGrid/plugins/slick.cellrangeselector.js"></script>
<script src="http://mleibman.github.io/SlickGrid/plugins/slick.cellrangedecorator.js"></script>
<script src="http://mleibman.github.io/SlickGrid/plugins/slick.rowselectionmodel.js"></script>
<script src="http://mleibman.github.io/SlickGrid/plugins/slick.autotooltips.js"></script>
<script src="http://mleibman.github.io/SlickGrid/plugins/slick.cellcopymanager.js"></script>
<script src="my.js"></script>
</head>
<body>
<div id="myGrid" style="width:100%;height:300px;"></div>
</body>
</html>
$(function () {
var grid;
// Addition Start
var columns = [{
id: "column",
name: "",
field: "column",
//selectable: false,
focusable: false
},
{
id: "data",
name: "Data",
field: "data"
}];
var options = {
enableCellNavigation: true,
enableColumnReorder: false
};
// Addition End
var data = []; // Addition
for (var i = 0; i < 30; i++) {
data[i] = {
pbc_id: "00" + i,
task: "Task " + i,
due_date: "02/02/2017"
};
}
grid = new Slick.Grid("#myGrid", data, columns, options);
grid.setSelectionModel(new Slick.CellSelectionModel());
grid.registerPlugin(new Slick.AutoTooltips());
// set keyboard focus on the grid
grid.getCanvasNode().focus();
var copyManager = new Slick.CellCopyManager();
grid.registerPlugin(copyManager);
copyManager.onPasteCells.subscribe(function (e, args) {
if (args.from.length !== 1 || args.to.length !== 1) {
throw "This implementation only supports single range copy and paste operations";
}
var from = args.from[0];
var to = args.to[0];
var val;
for (var i = 0; i <= from.toRow - from.fromRow; i++) {
for (var j = 0; j <= from.toCell - from.fromCell; j++) {
if (i <= to.toRow - to.fromRow && j <= to.toCell - to.fromCell) {
val = data[from.fromRow + i][columns[from.fromCell + j].field];
data[to.fromRow + i][columns[to.fromCell + j].field] = val;
grid.invalidateRow(to.fromRow + i);
}
}
}
grid.render();
});
grid.onAddNewRow.subscribe(function (e, args) {
var item = args.item;
var column = args.column;
grid.invalidateRow(data.length);
data.push(item);
grid.updateRowCount();
grid.render();
});
// Move DocumentViewModel inside "$(function ()"
var DocumentViewModel = function () {
var self = this;
self.sendGridData = function () {
var data = $("myGrid");
//TODO: access the grid data and convert the data to a json string
var Data_Grid = grid.getData();
var myJsonString = JSON.stringify(Data_Grid);
// $.ajax({
// async: true,
// type: "POST",
// dataType: "json",
// url: '/MyService/SubmitRequest',
// data: ,
// success: function (response) {
// alert("success");
// },
// error: function (xhr, textStatus, exceptionThrown) {
// alert("error");
// }
// });
};
self.sendGridData(); // Addition Trigger our local function
};
// Addition : Trigger our function to prove we can access the grid's data
DocumentViewModel();
})
I'm trying to make an XML based menu with JavaScript, XML and jQuery. I've been successful at getting the categories of the menu, but haven't been able to generate the items in the categories.
My script is as follows, and later in this thread, I've asked for suggestions for this code:
var animalsXMLurl = 'http://dl.dropboxusercontent.com/u/27854284/Stuff/Online/XML_animals.xml';
$(function() {
$.ajax({
url: animalsXMLurl, // name of file you want to parse
dataType: "xml",
success: function parse(xmlResponse) {
var data = $("item", xmlResponse).map(function() {
return {
id: $("animal_id", this).text(),
title: $("animal_title", this).text(),
url: $("animal_url", this).text(),
category: $("animal_category", this).text().split('/'),
};
}).get();
var first_item = category_gen(data, 0);
$('ul.w-nav-list.level_2').append(first_item);
var categnumber = new Array();
for (i = 1; i <= data.length; i++) //for splitting id, and getting 0 for category_number (1 or 2 or 3...and so on)
{
categnumber[i] = data[i].id.split('_');
console.log(categnumber[i][0]);
for (j = 1; j <= data.length; j++) //appending via a function.
{
var data_text = category_or_animal(data, categnumber, j);
console.log(data_text);
$('ul.w-nav-list.level_2').append(data_text);
}
}
function category_or_animal(d, catg, k) {
var catg1 = new Array();
var catg2 = new Array();
var catg1 = d[k].id.split('_');
if (d[k - 1]) {
var catg2 = d[k - 1].id.split('_');
//if(d[k-1].id)
if (catg1[0] != catg2[0])
return category_gen(d, k);
} else
return '</ul>' + animal_gen(d, k);
}
function category_gen(d, z) {
var category_var = '<li class="w-nav-item level_2 has_sublevel"><a class="w-nav-anchor level_2" href="javascript:void(0);"><span class="w-nav-title">' + d[z].category + '</span><span class="w-nav-arrow"></span></a><ul class="w-nav-list level_3">';
return category_var;
}
function animal_gen(d, z) {
var animal_var = '<li class="w-nav-item level_3"><a class="w-nav-anchor level_3" href="animals/' + d[z].url + '"><span class="w-nav-title">' + d[z].title + '</span><span class="w-nav-arrow"></span></a></li>';
return animal_var;
}
}, error: function() {
console.log('Error: Animals info xml could not be loaded.');
}
});
});
Here's the JSFiddle link for the above code: http://jsfiddle.net/mohitk117/d7XmQ/4/
In the above code I need some alterations, with which I think the code might work, so I'm asking for suggestions:
Here's the function that's calling separate functions with arguments to generate the menu in above code:
function category_or_animal(d, catg, k) {
var catg1 = new Array();
var catg2 = new Array();
var catg1 = d[k].id.split('_');
if (d[k - 1]) {
var catg2 = d[k - 1].id.split('_');
//if(d[k-1].id)
if (catg1[0] != catg2[0])
return category_gen(d, k);
} else
return animal_gen(d, k) + '</ul>';
}
At the if(catg1[0] != catg2[0]) it checks if the split string 1_2 or 1_3 is equal to 1_1 or 1_2 respectively. By split, I mean the first element: 1 .... if you have a look at the xml: [ :: Animals XML :: ], you'll see that the animal_id is in the format of %category_number% _ %item_number% ... So I need to create the menu with CATEGORY > ITEM (item=animal name)
Now if I could return category_gen() + animal() with animal(){ in a for loop for all the matching category id numbers} then maybe this could be complete! But I don't of a count script for conditioning the for loop (i=0;i<=count();i++)...
Would anyone know of how to get this script functioning?
Hard to tell what the provided JSFiddle is trying to do.
This is my best stab at it. I used JQuery to parse the XML out into categories and generate lists of items.
http://jsfiddle.net/d7XmQ/8/
"use strict";
var animalsXMLurl = 'http://dl.dropboxusercontent.com/u/27854284/Stuff/Online/XML_animals.xml';
$(function () {
var $menu = $('#menu');
$.ajax({
url: animalsXMLurl, // name of file you want to parse
dataType: "xml",
success: handleResponse,
error: function () {
console.log('Error: Animals info xml could not be loaded.');
}
});
function handleResponse(xmlResponse) {
var $data = parseResponse(xmlResponse);
createMenu($data);
}
function parseResponse(xmlResponse) {
return $("item", xmlResponse).map(function () {
var $this = $(this);
return {
id: $this.find("animal_id").text(),
title: $this.find("animal_title").text(),
url: $this.find("animal_url").text(),
category: $this.find("animal_category").text()
};
});
}
function createMenu($data) {
var categories = {};
$data.each(function (i, dataItem) {
if (typeof categories[dataItem.category] === 'undefined') {
categories[dataItem.category] = [];
}
categories[dataItem.category].push(dataItem);
});
$.each(categories, function (category, categoryItems) {
var categoryItems = categories[category];
$menu.append($('<h2>').text(category));
$menu.append(createList(categoryItems));
});
}
function createList(categoryItems) {
var $list = $('<ul>');
$.each(categoryItems, function (i, dataItem) {
$list.append(createItem(dataItem));
});
return $list;
}
function createItem(dataItem) {
return $('<li>').text(dataItem.title);
}
});
You can solve this without using any for/while loop or forEach.
function myCounter(inputWords) {
return inputWords.reduce( (countWords, word) => {
countWords[word] = ++countWords[word] || 1;
return countWords;
}, {});
}
Hope it helps you!
I've created a dynamic listview from database on my jQuery mobile #page1.
That works all perfect. I can see a list with all items from my database (ID, name ...)
Now I want to pass the ID garm.ID from my database item to the next page, after I've clicked on a item in the listview.
My JavaScript:
$(document).on("pagecreate", "#page1",function(){
$(function() {
$.ajaxSetup( {
"async": false
} );
$.getJSON("http://server/kas1.js", function(data) {
for(var i = 0; i < data.length; i++) {
var garm = data[i];
$.getJSON("http://server/kas2.js", function(data) {
var no = data[0].no;
$("#content-page1").append(
"<ul data-role=\"listview\">" +
"<li><a href=\"#page2\">" +
"<h2>Hello</h2>" +
"<p>Status:"+data[0].no+"</p>" +
"</a></li>" +
"</ul><br>"
);
});
}
});
$.ajaxSetup( {
"async": true
} );
});
});
You can see the line: "<li><a href=\"#page2\">" +
With this link you will redirect to the next page and on the next page I want to use the passed ID.
Try this:
$(document).on("pagecreate", "#page1",function(){
$(function() {
$.ajaxSetup( { "async": false } );
$.getJSON("http://server/kas1.js", function(data) {
for(var i = 0; i < data.length; i++) {
var garm = data[i];
$.getJSON("http://server/kas2.js", function(data) {
var no = data[0].no;
$("#content-page1").append(
"<ul data-role=\"listview\">" +
"<li><a href='#page2?garm_id='" + garm.ID + ">" +
"<h2>Hello</h2>" +
"<p>Status:"+data[0].no+"</p>" +
"</a></li>" +
"</ul><br>"
);
});
}
});
$.ajaxSetup( { "async": true } );
});
});
On page two:
function queryStringParameters (keyValueString) {
var query_string, whole_query_string, query_string_obj = {};
if (typeof keyValueString === "undefined") {
whole_query_string = window.location.search;
if (whole_query_string[0] === "?") {
query_string = whole_query_string.replace('?', '');
} else {
query_string = whole_query_string;
}
} else {
query_string = keyValueString
}
var query_string_array = query_string.split('&');
if (query_string !== '') {
for (var i = 0; i < query_string_array.length; i++) {
var query = query_string_array[i],
query_array = query.split('=');
query_string_obj[query_array[0]] = query_array[1] || '';
}
return query_string_obj;
} else {
return {};
}
}
var hash = window.location.hash,
queryString = hash.split('?')[1],
garm = queryStringParameters(queryString),
garm_id = garm.id;
I hope this works:
'<li><a href="#page2,garmId='+ garm.ID +'">'
then, in page 2 you can (hopefully) parse the hashtag to get the id
Hope this helps, cheers
I've been trying to implement JavaScript thats read my twitter account ant return to me the latest 2 tweeties...
I try to use the XML but, it doesn't work well.
There is a easy way to do this?
<script>
var ajax = "";
$(function () {
ret_tweets(1);
$('body').data('page', 1);
in_scroll();
});
function in_scroll() {
$(window).scroll(function () {
if (($(window).scrollTop() + $(window).height() + 10) >= $(document).height()) {
$(window).unbind('scroll');
ajax.abort();
ret_tweets($('body').data('page'));
}
});
}
function retorna_tweets(pagina) {
$('#list-tweets').append('<li class="Loading">Loading</li>');
var screen_name = 'new';
var url = 'http://api.twitter.com/1/statuses/user_timeline.json?callback=?';
$('body').data('page', paging + 1);
ajax = $.getJSON(url, {
screen_name: screen_name,
page: page
}, function (tweets) {
$('.carregando').fadeOut(function () {
for (x in tweets)
$('#list-tweets').append('<li>' + tweets[x].text + '</li>');
in_scroll();
$(this).remove();
});
});
}
</script>
There is another solution using JAvaScript?
Twitter offers solution to this:
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>
<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/takewara.json?callback=twitterCallback2&count=2"></script>
The above will get last two tweets from user takewara (yes, thats me on twitter :) )
EDIT
here is also snippet from my page how do i do it:
<h2 style="display: none;" >Actualities</h2>
<div id="twitter_div">
<h2 style="display: none;" >Twitter Updates</h2>
<ul id="twitter_update_list"></ul>
..older tweets
</div>
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"> </script>
<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/takewara.json?callback=twitterCallback2&count=2"></script>
</div>
</div>
Try This, should Work:
The JavaScript:
function twtLnks(txt) {
p = txt.split(" ");
txt = "";
for (var i = 0; i < p.length; i++) {
var str = p[i];
var lnk = "https://twitter.com/#!/";
if (str.indexOf("#") != -1) { str = '' + str + ''; }
if (str.indexOf("#") != -1) { str = '' + str + ''; }
if (str.indexOf("http://") != -1) { str = '' + str + ''; }
txt += str + " ";
} return txt;
}
function tweets() {
if ($('.homeTwitter').length) {
$('.homeTwitter').append('<span>Loading.</span>');
//Here put your account
var sn = 'YourAccount';
var u = 'https://api.twitter.com/1/statuses/user_timeline.json?callback=?';
var t = $.getJSON(u, { screen_name: sn }, function(twt) {
$('.homeTwitter span').fadeOut("fast", function() {
$(".homeTwitter").append("<ul></ul>");
for (var i = 0; i < 1; i++) {
if (twt[i]) {
var txt = twtLnks(twt[i].text);
$(".homeTwitter ul").append('<li>' + txt + '</li>');
} else {
break;
}
}
$(".homeTwitter").append('#' + sn + '');
$(this).remove();
});
});
}
}
$(document).ready(function() {
tweets();
});
IN C#
<div class="homeTwitter">
<h2>Twitter</h2>
</div>