ASP.NET MVC with YUI - asp.net

I am using ASP.NET MVC 2. I have played around you the YUI samples that can be found on http://developer.yahoo.com/yui/2/. I have been wondering if any one has had the time to use the YUI controls in an MVC app?
I want to start using the datatable and display my results from a SQL Server in this datatable. How is this possible? Any samples would be appreciated.
Thanks

The YUI controls are plain javascript controls and are server agnostic meaning that they can be used with any server side technology as long as you format the results as expected. So here's an oversimplified example of the data table control in action using AJAX and JSON to populate its data:
Controller:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Assets()
{
// TODO: fetch data from SQL using a repository
var data = new
{
ResultSet = Enumerable.Range(1, 25).Select(i => new
{
Title = "title " + i,
Phone = "phone " + i,
City = "city " + i
})
};
return Json(data, JsonRequestBehavior.AllowGet);
}
}
and in the view:
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.1/build/yuiloader/yuiloader-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.1/build/event/event-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.1/build/connection/connection-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.1/build/json/json-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.1/build/dom/dom-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.1/build/element/element-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.1/build/datasource/datasource-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.1/build/datatable/datatable-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.1/build/button/button-min.js"></script>
<script type="text/javascript">
YAHOO.util.Event.addListener(window, 'load', function () {
YAHOO.example.XHR_JSON = new function () {
var myColumnDefs = [
{ key: 'Title', label: 'Name', sortable: true },
{ key: 'Phone' },
{ key: 'City' },
];
this.myDataSource = new YAHOO.util.DataSource('<%= Url.Action("assets") %>');
this.myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
this.myDataSource.responseSchema = {
resultsList: 'ResultSet',
fields: ['Title', 'Phone', 'City' ]
};
this.myDataTable = new YAHOO.widget.DataTable('json', myColumnDefs,
this.myDataSource);
};
});
</script>
<div id="json"></div>
The datatable control is very powerful and contains many customizations like paging, sorting, ... The documentation is pretty extensive and is worth reading to see examples in action. Armed with FireBug you could look at the requests and response parameters being exchanged between the client and the server in order to replicate each example.

Related

Multiple Google Charts on Same Page from same Data using Entity model

I'm trying to setup a Web Page using the same data that is being pulled for the first chart. Data is being pulled by an edmx entity model. The code below works for single graph. I want to add a Pie Chart on the same page as well using the same data. All the examples I've seen are for graphs using static data. My code is below, I know I would need to just reproduce what I have in some fashion. Thanks,
<script type="text/javascript" src="https://www.google.com/jsapi">
</script>
#section Scripts{
<script>
$(document).ready(function () {
//Load Data Here
var chartData = null;
$.ajax({
url: '/GoogleChart/GetSalesData',
type: 'GET',
dataType: 'json',
data: '',
success: function (d) {
chartData = d;
},
error: function () {
alert('Error!');
}
}).done(function () {
drawChart(chartData);
});
});
function drawChart(d) {
var chartData = d;
var data = null;
data = google.visualization.arrayToDataTable(chartData);
var view = new google.visualization.DataView(data);
view.setColumns([0, {
type: 'number',
label: data.getColumnLabel(0),
calc: function () { return 0; }
}, {
type: 'number',
label: data.getColumnLabel(1),
calc: function () { return 0; }
}, {
type: 'number',
label: data.getColumnLabel(2),
calc: function () { return 0; }
}]);
var chart = new google.visualization.ColumnChart(document.getElementById('visualization1'));
var options = {
}
var runFirstTime = google.visualization.events.addListener(chart, 'ready', function () {
google.visualization.events.removeListener(runFirstTime);
chart.draw(data, options);
});
chart.draw(view, options);
}
google.load('visualization', '1', { packages: ['corechart'] });
</script>
<div id="visualization1" style="width:900px; height:500px"></div>
}
first, recommend using...
<script src="https://www.gstatic.com/charts/loader.js"></script>
not...
<script src="https://www.google.com/jsapi"></script>
according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader.js from now on.
note: the load statement will be the only difference, as seen below...
next, you can draw as many charts as necessary,
after the load statement has completed
you must set a callback to know for sure,
that google charts has loaded all of the requested packages...
multiple packages can be loaded at the same time
google.charts.load('current', {
callback: loadData,
packages: ['corechart', 'table']
});
the callback will also wait for the document to finish loading...
as such, $(document).ready isn't needed
recommend setup similar to following...
<script src="https://www.gstatic.com/charts/loader.js"></script>
#section Scripts{
<script>
function loadData() {
$.ajax({
url: '/GoogleChart/GetSalesData',
type: 'GET',
dataType: 'json',
data: '',
}).fail(function (jq, text, errMsg) {
console.log(text + ': ' + errMsg);
}).done(function (jsonData) {
drawCharts(jsonData);
});
}
function drawCharts(jsonData) {
var chartData = google.visualization.arrayToDataTable(jsonData);
var chartCol = new google.visualization.ColumnChart(document.getElementById('visualization-col'));
chartCol.draw(chartData);
var chartPie = new google.visualization.PieChart(document.getElementById('visualization-pie'));
chartPie.draw(chartData);
var chartTable = new google.visualization.Table(document.getElementById('visualization-table'));
chartTable.draw(chartData);
}
google.charts.load('current', {
callback: loadData,
packages: ['corechart', 'table']
});
</script>
<div id="visualization-col"></div>
<div id="visualization-pie"></div>
<div id="visualization-table"></div>
}
note: each chart has a specific data format
although most of the charts in 'corechart' will be fine,
not all charts may work with the same data table...

how to add section Scripts to asp.net mvc Razor View without layout page

My mvc view layout is null. how can i add script inside view.
#{
Layout = null;
}
#section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$('#txtChild1').on('change', function () {
$("#C1Age1").show();
});
});
</script>
}
Error show
cannot resolve section 'Scripts'
If you use Layout = null then you don't need to use #section Scripts any more. you can simply use script tag.
Example:
#{
Layout = null;
}
<script type="text/javascript">
$(document).ready(function () {
$('#txtChild1').on('change', function () {
$("#C1Age1").show();
});
});
</script>
If you are not using layout page then you need not to add section. add scripts as you add them on a html page.
#{
Layout = null;
}
<script type="text/javascript">
$(document).ready(function () {
$('#txtChild1').on('change', function () {
$("#C1Age1").show();
});
});
</script>
You can also add script block without section if it is not mandatory.

Ajax Not returning Data to Action ASP.net MVC

I am new to MVC and facing a problem with accessing data via ajax in action of my ASP.NET Application.
Here is my Ajax Code:
$('.testBtn').click(function() {
$.ajax({
type: 'GET',
data: { id: 10 },
url="#Url.Action("GetData", "Consultation")",
success:function()
{
}
});
});
And here is my action inside the controller:
public ActionResult GetData(int id)
{
string x=id.ToStrring();
return null;
}
For testing I am just passing a static integer and getting its value inside my action.
On clicking the button I am getting the following error:
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult GetData(Int32)' in 'careshade_mvc.Controllers.ConsultationController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Here is working code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.testBtn').click(function () {
$.ajax(
{
url: 'Consultation/GetData',
type: "POST",
data: { id: 10 },
success: function (result) {
}
});
});
});
</script>
</head>
<body>
<input type="button" class="testBtn" value="ClickHere" name="button">
</body>
</html>
Try this:
$(document).ready(function() {
var id = 10;
$('.testBtn').click(function () {
$.ajax(
{
url: 'Consultation/GetData/' + id,//instead data: { id: 10 },
type: "GET",
success: function (result) {
}
});
});
});
You need to use a colon(:) character after url not the equals(=) sign.
Simply change:
url="#Url.Action("GetData", "Consultation")",
To this:
url:"#Url.Action("GetData", "Consultation")",
This was the only change I had to make to make the call work.Hope it helps you!

Using Typeahead.js with ASP.NET WebAPI

I am trying to make it work with Web-Api and typeahead.js, i think i am missing something and this code is not working, what i am missing here, here is the complete code i used.
my controller code
public IEnumerable<Songs> GetSongs()
{
string searchTerm="";
List<Songs> songList = new List<Songs>();
songList.Add(new Songs { Name = "Addat", Artist = "Aatif Aslam", Year = "2007" });
songList.Add(new Songs { Name = "Woh Lamhey", Artist = "Jal - The band", Year = "2008" });
songList.Add(new Songs { Name = "Kryptonite", Artist = "3 Doors Down", Year = "2009" });
songList.Add(new Songs { Name = "Manja", Artist = "Amit Trivedi", Year = "2013" });
songList.Add(new Songs { Name = "Tum hi ho", Artist = "Arjit Singh", Year = "2013" });
songList = songList.Where(m => m.Name.Contains(searchTerm)).ToList();
return songList;
}
here is the helper class
public class Songs
{
public string Name { get; set; }
public string Year { get; set; }
public string Artist { get; set; }
}
simple html page with javascript call
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script src="Scripts/typeahead.bundle.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
<link href="Content/typeahead.css" rel="stylesheet" />
<script type="text/javascript">
$(document).ready(function () {
$("#search-box2").typeahead({
name: 'songs',
displayKey: 'Name',
remote: {
url: 'http://localhost:8822/api/Search/GetSongs?searchTterm=%QUERY',
dataType: 'json'
}
});
});
</script>
</head>
<body>
<input type="text" id="search-box2" class="form-control" />
</body>
</html>
This is what you can do :
$(document).ready(function () {
var songlist = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('songs'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10,
remote: 'http://localhost:8822/api/Search/GetSongs?searchTterm=%QUERY'
});
// kicks off the loading/processing of `local` and `prefetch`
songlist.initialize();
// debugger;
// passing in `null` for the `options` arguments will result in the default
// options being used
$('#search-box2').typeahead(null, {
name: 'song',
displayKey: 'Name',
// `ttAdapter` wraps the suggestion engine in an adapter that
// is compatible with the typeahead jQuery plugin
source: songlist.ttAdapter()
});
});
More Details from documentation

Calling ASP.NET MVC Controller explicitly via AJAX

I know that I can use following piece of code to refresh a div:
<%=Ajax.ActionLink( "Update", "Administration", new AjaxOptions { UpdateTargetId = "grid", LoadingElementId = "grid-wait" } ) %>
But this creates a link; user will have to click on it to get the view refreshed.
How can I make it automatic, i.e., like say if I want the grid to be refreshed after every five seconds?
Try this:
<p id="CurrentDateTime"></p>
<script src="../../Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
window.setInterval(updateDateTime, 5000);
function updateDateTime() {
$.get("GetCurrentDate?rnd=" + Math.random(1000), {}, function (r) {
$("#CurrentDateTime").html(r);
}, "text");
}
</script>
public ActionResult GetCurrentDate()
{
return Content(DateTime.Now.ToString("U"));
}

Resources