Tuesday, April 18, 2017
Wednesday, November 30, 2011
MVC, Single Result, and PartialViews
Let's say you have a controller that looks like this
public ActionResult Index(IPrincipal principal, int? pageNumber)
public ActionResult Index(IPrincipal principal, int? pageNumber)
{
return View(GetData(principle, pageNumber));
}
where the result contains
result.Vegies where these are List<{ string Label, string Value }>
result.Proteins where these are List<{ string Name, string Value }>
at the Index.cshtml, you can do this.
<table style="width: 800px; width: auto "> <tr> <td style="width: 240px;">@Html.Partial("VegieView")<td><td style="width: 560px">@Html.Partial("ProteinView")<td><tr> <table>at the ../Shared/VegieView.cshtml you can do
@{ var oVegies = Model.Vegies as IEnumerable<Vegies>; } @foreach (var x in oVegies )
{ foreach (var y in x.Vegies) { <div>@Html.DisplayFor(j=> y.Label)<div>} }at the ../Shared/ProteinView.cshtml you can do
@{ var oProteins = Model.Proteins as IEnumerable<Proteins>; } @foreach (var x in oProteins)
{ foreach (var y in x.Proteins) { <div>@Html.DisplayFor(j=> y.Name)<div>} }So, a single controller call can update all shared view models..:-) neat!I know, you are welcome.
Sorting and Filtering Data Set with JavaScript and jQuery.
When working with potentially large corporate data sets, filtering and sorting should be done at the back end with ajax call. Even though, filtering and sorting can be done cleverly by JavaScript, potential for downloading large data set and problems with the IE8 JavaScript error (O^2) can catch up with you. I don't recommend joining, merging, and other sql-like operations with JavaScript. Most sorting and Filtering requires at minimum O^2.
Also, when building a grid that reads any data set, the endpoint should always have paging related parameters like PageNumber, PageSize, and few others. The only part of the data set that's relevant to the current display should be retrieved. Data joining should not be done at the web UI level.
For the JSONData, you could build out a string that matches with the class signature, DataContract
Also, when building a grid that reads any data set, the endpoint should always have paging related parameters like PageNumber, PageSize, and few others. The only part of the data set that's relevant to the current display should be retrieved. Data joining should not be done at the web UI level.
$.ajax({ type: "POST", url: "http://localhost:5000/Search/GetData", data: JSONData, }).done(function (msg) { alert("Data Saved: " + msg); });
For the JSONData, you could build out a string that matches with the class signature, DataContract
public class SearchResult { public JsonResult data { get; set; } public int PageNumber { get; set; } public int PageSize { get; set; } public int PageCount { get; set; } public int DataCount { get; set; } }
public class SearchPackage { public SearchItem[] Items { get; set; } public int PageNumber { get; set; } public int PageSize { get; set; } }
public class SearchItem { public string FieldName { get; set; } public string Value { get; set; } public SortDirection SortDirection { get; set; } }
var JSONData = { "SearchItem": [{ "fieldName": "LastName", "value": "Smith", "sortDirection": "SortDirection.ASC" }, { "fieldName": "FirstName", "value": "John", "sortDirection": "SortDirection.DESC"}]};If you are passing an url value for the data, you can dourl: "http://localhost:5000/Search/GetData?fieldNames=LastName&fieldNames=FirstName&values=Smith&values=John&sortDirections=SortDirection.ASC&sortDirections=SortDirection.Desc";
[HttpPost] public JsonDataResult GetData(List<string> fieldNames, List<string> values, List<int> sortDirections) {using (var proxy = searchFactory.CreateChannel()) {SearchResult oSearchResult = SearchFactory.GetRequestPackage(Transform(fieldNames, values, sortDirections)); return Json(oSearchResult );} }Since there are two parameters called the fieldNames, such parameters is like passing a ListfieldName.
Monday, November 21, 2011
Triggering Associated Event
You can trigger an event of a HTMLElement calling the onclick event of the element.
Let's say, you have <div><ul><li><dl><dd parent="MotorCycle">Honda VFR1200Fdd>dl>li>ul>div>
Then you can do
<div onclick="triggerFilterEvent(this)">Honda VFR1200Fdiv>
The reason you do is so that you don't have duplicated method calls. The parameters allow you to traverse through its DOM tree.
function triggerFilterEvent(object1) {
var category = $(object1).attr("parent");
var root = $("div");var value = $(object1).text();
var dls = $(root).find("ul li dl"); var dds = $(dls).find("dd[parent='" + category + "']"); for (var x = 0; x < $(dds).length; x++) { var dd = $(dds)[x]; if (dd.innerText === value) { $(dd).click(); } } }
you could do var dd =$("div ul li dl dd[parent='"+category +"']").click(); but on IE version < 9, the code would encounter problems.You also note that I did the for loop instead of the jQuery.each().
Friday, November 18, 2011
Ajax Call using Asp.net MVC Controller
I used to make a ajax call to .svc file.
ASP.Net, Ajax, Restful call.
The following example is a C# restful class makes the rest call possible and the JavaScript code that calls the AjaxDataService.svc end point.
C#
ASP.Net, Ajax, Restful call.
The following example is a C# restful class makes the rest call possible and the JavaScript code that calls the AjaxDataService.svc end point.
C#
[ServiceContract] public interface ITestService { [OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetJsonData/{param}")] string GetJsonData(string text); }[ServiceBehavior(Name = "WCFHost.AjaxDataService", Namespace = "http://localhost:2469/",InstanceContextMode = InstanceContextMode.PerCall,
ConcurrencyMode = ConcurrencyMode.Multiple), AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class TestService : ITestService {public string GetJsonData(string param) { return GetData2(param);}}
JavaScript
function AjaxGrid(id) {
this.GetJsonData = function (object1, param) { var statusNode = $(".Status"); jQuery.ajax({ url: "WCFHost/AjaxDataService.svc/GetJsonData?param=" + param, type: "POST", dataType: "json", async: true, beforeSend: function () { statusNode.text("Do Something on Before"); }, success: function (xhr) { statusNode.text("Do Something on Success"); }, complete: function () { statusNode.text("Do Something on Complete"); }, error: function () { statusNode.text("Do Something on No Way!"); } }); }}
However, with asp.net MVC, you can make calls directly to specified controller.
in a AwesomeController.cs
public class SearchController : Controller {
[HttpPost] public JsonResult GetJsonData(string param) { return Json(GetData2(param)); }}JavaScript
function AjaxGrid(id) {
this.GetJsonData = function (object1, param) { var statusNode = $(".Status"); jQuery.ajax({ url: "AwesomeController/GetJsonData?param=" + param, type: "POST", dataType: "json", async: true, beforeSend: function () { statusNode.text("Do Something on Before"); }, success: function (xhr) { statusNode.text("Do Something on Success"); }, complete: function () { statusNode.text("Do Something on Complete"); }, error: function () { statusNode.text("Do Something on No Way!"); } }); }}
linq js
In JavaScript (even with other framework library), there may not be some very easy dot notation way to filter data.
/// this is O(n^2) ~= f(x) = O * nO
You often have to go through the whole collection then to push values into another array object to collect the values that you want, filtering.
Data Structure
[ FieldName : string, Filters : [ IsSelected : boolean, Value : variant ] ]
Typical JavaScript Filtering Pattern
var data = fetchData(); // gets the ajax data in Json array
var filteredData = new Array(); // where new filtered
var filterListLimit = getFilteredListLimit(); // number of times which the category changes
/// this is O(n^2) ~= f(x) = O * nO
for (var q = 0; q < data.length; q++) {
var oX = data[q]; // for convenience
var includeCounter = 0;
for (var f = 0; f < FilterList.length; f++) {
if (oX[FilterList[f][0]] == FilterList[f][1]) {
includeCounter++;
}
}
if (includeCounter == filterListLimit) {
filteredData.push(oX);
}
}
In C#, you can do
var filteredData =( from p in data
where p.key == 5
select new {
Brand = p.Brand,
Name = p.Name,
Year = new DateTime(p.Date).Year
}).Distinct();
with linq.js, you can do
var filteredData = Enumerable.From(data)
.Where(function(x) { return ( x.key == 5 ) })
.Select("o=> { Brand : o.Brand, Name : o.Name, Year : o.Year "}).Distinct().ToArray();
Neat ... :-)
There are more examples and a file at the below link.
jquery.each inefficient
I have discovered that the jQuery.each() call is inefficient.
jQuery.each() maybe f(x) > n; where f(x) maybe n^i or xn. i > 1.
I recommend using the for loop instead.
jQuery.each() maybe f(x) > n; where f(x) maybe n^i or xn. i > 1.
I recommend using the for loop instead.
Subscribe to:
Posts (Atom)