February 27, 2014
@ 09:21 AM
It's the tie to go along with jQuery's tux, and Backbone.js's suspenders

Don't need write your own utility.js...use underscore.js.

Underscore is more suited to data manipulation and brings many Ruby methods to JavaScript. There is some crossover, but not enough to make them mutually exclusive.

Categories: JQuery

when use JqueryMobie in form, after submit, if redirect, it will have 302 find error.
jquery ajax submit was fired.


1. regular form, add data-ajax="false" in the from
2. MVC from,
 @using (Html.BeginForm(null,null,FormMethod.Post, new { data_ajax="false" }))

notice "data_ajax" in code bind, but it display data-ajax in the view.

Categories: JQuery | Mobile | MVC

Note: below solution just for not using InAppBrowser plugin,

When InAppBrowser plugin was add correctly, simply call open.window(url,"_system") will open url in new Browser.

First check your your config.xml , You can define your whiteList by change , for detail how to do it, please check http://docs.phonegap.com/en/1.9.0/guide_whitelist_index.md.html and will make any url not in white list be open in new safari window instand of InWebView.

If your url is in your white list (ex, you use * make all urls are allowed) but you want to open some url in safari, You have to add extra code to do that.

My solution is like below: first I define a function to open safary url:

LaunchNewWindow: function (url) {       
   if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {         
    window.open(url+"#_external", "_blank");}
    window.open(url, "_blank");

then you have to change code in CordovaLic\Classses\CDViewController.m to handle your spacial url: I added it in line685 :

else {

// start stoneskin's change: force open external url in safari                              
               if ([[url scheme] isEqualToString:@"http"] || [[url scheme] isEqualToString:@"https"]) {
NSString *myurlstr = [url absoluteString];
if ([myurlstr rangeOfString:@"#_external"].location != NSNotFound){
myurlstr = [myurlstr stringByReplacingOccurrencesOfString:@"#_external" withString:@""];
NSURL *myurl = [NSURL URLWithString:myurlstr];
[[UIApplication sharedApplication] openURL:myurl];
return NO;
//end start stoneskin's change if ([self.whitelist schemeIsAllowed:[url scheme]]) { return [self.whitelist URLIsAllowed:url]; } else { if ([[UIApplication sharedApplication] canOpenURL:url]) { [[UIApplication sharedApplication] openURL:url]; } else { // handle any custom schemes to plugins [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginHandleOpenURLNotification object:url]]; } } return NO; }
Don't forget this code only working for Phonegap wrapped app.

Categories: JQuery | Mobile | XCode iOS

Yesterday I test cross domain post against MVC successfully. So how about post to WebAPI?

But first try I failed and got error message like "Optional parameter 'user' is not supported by 'FormatterParameterBinding'.

after some research and test, I notice webapi [fromBody] parameters binding only take Model class as parameter.
//var data = "user=a" not owrk...string didn't have properties of user;
public string Test([FromBody] string user)
            return "user:" + user;

I have to change code like below:
public string Test([FromBody] User user)
            return "user:" + user;

  public class User
        public string Name { get; set; }

        public string Pwd { get; set; }
And test to post by jQuery
$.post('http://localhost:6660/api/task/test/0/t', { Name: 'a' ,Pwd:'b'});

and everything works

Categories: Asp.net | JQuery | MVC

I don't want to use jsonP because it only can use "GET" method and all the data can be viewed on url.
After many search and failed test code. Finally I got below solution:

1. Enable CORS on server,
  a. asp.net site said you can enable cors for webapi: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api . unfortunately, it require preview version of visual studio 2013.
  b. http://enable-cors.org/ site offer the methods to enable cors on IIS7, But it not works in my test.
  c. so I have to add the Access-Control-Allow-Origin=* to the response header by code myself.
    Simplest way is  adding this function in global.asax.cs
   protected void Application_BeginRequest(object sender, EventArgs e)
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

my test Action:
 public ContentResult Test(FormCollection formValues,string user="", string pwd="" )
            dynamic flexible = new ExpandoObject();
            flexible.UserName = user;

            var dictionary = (IDictionary<string, object>)flexible;
            dictionary.Add("IsSuccess", true);

            var re= JsonConvert.SerializeObject(dictionary); 
            return  Content(re);

2. It's not finish yet. you can see the correct response was return to the client in Fiddle or firebug, but the JQuery ajax call success not be fired. we have to do some more code on client side:
var loginUrl = 'http://localhost:6660/home/test';
        var data = "user=a&pwd=b";
            type: 'POST',
            url: loginUrl,         
            data: data,
            sucess:function(re) {
                //never reached here
            error: function (jqXHR, error, errorThrown) {
                //handle err
            complete: function (re, status) {
                if (status == 'success') {
                    var reObj = JSON.parse(re.responseText);

Yub!  date was get from cross domain server. this even working open html file directly.

Categories: Asp.net | C# | JQuery | MVC

Server side code in controller:
     public ContentResult TaskJsonP(string callback,int id)
            var model = service.GetTaskDetails(new TaskDetailRequest() { Id = id });
            //return Json(model, JsonRequestBehavior.AllowGet);
            return Content(String.Format("{0}({1});",
          new JavaScriptSerializer().Serialize(model)),          

Client side you can open any page and try below:
                       alert (value)              },

Categories: Asp.net | C# | Html5 | JQuery | MVC

 Web Api:  vs2013 only
1. install cors package through package manager console
Install-Package Microsoft.AspNet.WebApi.Cors -pre -project WebService

2. Add to api cofig
 public static class WebApiConfig
        public static void Register(HttpConfiguration config)
            // New code

                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
3. enable on apiController
namespace WebService.Controllers
    [EnableCors(origins: "http://myclient.azurewebsites.net", headers: "*", methods: "*")]
    public class TestController : ApiController
        // Controller methods not shown...
4. some time you need $.support.cors = ture; before you make jsonp call

for WCF, congig it in webHttpbinding section of web.config:

        <binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" />

If you use SignalR.
var hubConfiguration = new HubConfiguration();
hubConfiguration.EnableCrossDomain = true;

Client code that specifies a cross-domain connection (with the generated proxy)
$.connection.hub.url = 'http://fabrikam.com/'

Client code that specifies a cross-domain connection (without the generated proxy)

var connection = $.hubConnection('http://fabrikam.com/');

Categories: JQuery | MVC | WCF

Tools-> Library Package Manager -> Package Manager Console

PM> Install-Package jQuery-vsdoc -Version 1.10.2
PM> Install-Package jquery.mobile
Install-Package Microsoft.AspNet.SignalR -Version 1.1.3
PM> Install-Package knockoutjs
PM> Install-Package Modernizr
PM> Install-Package jQuery.UI.Combined

Categories: JQuery | Visual studio 10/up

August 13, 2013
@ 10:12 AM
1. Config global to use WebApi in MVC4
 protected void Application_Start()



2. Add your mapping in App_Start folder WebApiConfig.cs
public static class WebApiConfig
        public static void Register(HttpConfiguration config)
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
             name: "GetTaskApi",
             routeTemplate: "api/{controller}/{action}/{id}/{token}",
             defaults: null
            name: "ApiById",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: new { id = @"^[0-9]+$" }

            name: "ApiByName",
            routeTemplate: "api/{controller}/{action}/{name}",
            defaults: null,
            constraints: new { name = @"^[a-z]+$" }

            name: "ApiByAction",
            routeTemplate: "api/{controller}/{action}",
            defaults: new { action = "Get" }
3 Add you WebApi Controller
public class TaskController : ApiController
        // http://localhost:45897/api/task/1
        public TaskDetailResponse Get(int id)
                    return  apiService.GetTaskDetails(new TaskDetailRequest(){Id=id});
        // http://localhost:45897/api/task/gettask/1/testtoken
        public TaskDetailResponse GetTask([FromUri]TaskDetailRequest request)
            var response = apiService.GetTaskDetails(request);
            return response;


4. in Firefox and Chrome, if you visit the link, it will return xml, but in IE, it will let you save a json file

5. User jQuery.getJSON to call the api
function getData() {
        var apiUrl = 'api/task';
        var id = 1;
        $.getJSON(apiUrl + '/' + id)
            .done(function (data) {
            .fail(function (jqXHR, textStatus, err) {

Categories: JQuery | MVC

March 18, 2013
@ 10:10 PM
  • Fast
  • Well documented
  • Easy to use
  • Chaining
  • Unlike Prototype it doesn't extend an object if you didn't specifically ask for it (try looping an array in Prototype)
  • easy-to-use Ajax (I love the $.ajaxSetup() function)
  • Nice event handlers
  • CSS selectors
  • filtering your selection
  • did I mention chaining?
  • Small (only 30 KB)
  • Nice little built-in effects.
  • Plugins
  • OOP (and other paradigms) done right.
  • Widget infrastructure done right.
  • Modules done right with all necessary goodies:
    • Lazy loading of modules dynamically.
    • Possibility to extract only necessary modules and build a custom one-file profile.
    • Asynchronous loading of modules if desired.
    • Simple integration with CDNs for heavy-duty web applications.
  • Sheer breadth of available modules in DojoX including graphics, charting, grids, and so on.
  • Ability to use it in non-browser environments.
  • Attention to details in widgets:
    • support for i18n (including LTR and RTL languages),
    • support for l10n (including standard date, currency, number formatting),
    • provisions for people with special needs (automatic high-contrast mode, keyboard-only support, and so on) — useful for regular users too, and mandatory for most government contracts.
  • Smart people in the community (last but not least) — as much as I love hand-holding for novices, at some point every developer becomes "seasoned" and needs much more than that.
reference: http://stackoverflow.com/questions/394601/which-javascript-framework-jquery-vs-dojo-vs

Categories: JQuery

    function delayTAbFocus(target) {
         //hach for ie7
        target.live('keydown', function(e) {
            var keyCode = e.keyCode || e.which;

            if (keyCode == 9) {
               var ind = target.attr("tabindex") + 1;
                for (var i = ind; i < 100; i++) {
                    var nextTarget = $('input[tabindex=' + ind + ']');
                    if (nextTarget != null && nextTarget.is(':visible') && nextTarget.is(':enabled')) {
                        setTimeout(function() { $('input[tabindex=' + ind + ']').focus(); }, 100);


My solution is when Tab keydown, focus the current form1 again, then find the next tabindex.
in this code, I have set all tabindex in no interval sequence..

Categories: JQuery

1. add data-bind attribution to your dropdown

     @Html.DropDownListFor(m => m.SelectCafeBuildVersion, Model.AutoDaploymentData.CafeBuildVersions, "", 
 { @class = "", @data_bind = "options: cafeBuildVersions,optionsText: 'Text',optionsValue:'Value'" })       
Notce here is "@data_bind", it will change to "data-bind" in the HTML automatictly.

2. in the ajax Call get json object from backend, and add a a viewmode:

                type: "post",
                url: "MyController/RefreshModelData",
                success: function (model) {                   
                 var   viewModel = {
                        cafeBuildVersions: ko.observableArray(model.AutoDaploymentData.CafeBuildVersions)
                error: function (v) {
                    alert("data error!");

That's it..

if not in ajax..you can get the modeldata from model do it in the View:
var modelData = @Html.Raw(Json.Encode(Model));
<script type="text/javascript">
    var initialData = <%= new JavaScriptSerializer().Serialize(Model) %>;

Categories: JQuery | MVC

December 14, 2012
@ 02:16 PM
To transfer the model object from MVC c# object to Knockout  javascript data object:
var modelData = @Html.Raw(Json.Encode(Model));
With the ModelData in js...you can do other as Knockout give to you.

reference url

Categories: JQuery | MVC

I saw many ppl have solution for add a watermaker to text fields.

But their solution is not what I want, because it set the value to the text field..and it will be submit with real data when you click submit button.

So I make some improvement.
My solution is use a div to display watermaker message:
  .watermark { color#999position:absolute }

<script type="text/javascript">
SetWatermaker(targetId,text) { var target = $('#' + targetId); target.after('<div class="watermark" style="position: absolute;" id="wm' + targetId + '">' + text + '</div>'); var p = $('#' + targetId).offset(); p.left = p.left + 8; p.top = p.top + 3; var targetWm = $('#wm' + targetId); targetWm.offset(p); target.focusout(function() {
if(target.val()=="")   targetWm.show();
   targetWm.hide();         }); target.focus(function() { targetWm.hide(); }); }

    $(document).ready(function () {        SetWatermaker("txtMACAddress""AA:BB:CC:DD:EE:FF");      });

Categories: JQuery

I got requirement to display all fields in one page to less than 20 characters,  and display full length when mouse over on tool-tip.
I decide to use jQuery implement this, Below is partial code in UserAdminView namespace..
 SetUpAccountInfo: function () {
            var limit = 20;
            var targets = $(".account-info dd").not("dd.nolimitdisplay");
            targets.each(function () {
                UserAdminView.SetUpDisplayLimit($(this), limit);
        SetUpBaseService: function () {
            var limit = 50;
            var targets = $(".base-service dd");
            targets.each(function () {
                UserAdminView.SetUpDisplayLimit($(this), limit);
            // UserAdminView.SetUpDisplayLimit(target, limit);
        SetUpDisplayLimit: function (target, limit) {
            var fullMsg = target.html();
            if (fullMsg.length > limit) {
                target.html(fullMsg.substring(0, limit) + "...");
            target.attr('title', fullMsg);

Categories: JQuery

A simple test,
     url: "http://localhost:45166/userAdmin/UserAccountInfo/?child=true&json=true",
     dataType: 'jsonp',
     success: function(json) {

         //jsonp return a javascript
         // callback({json:value})
     error: function() {


in the Controller

return a javascript as ActionResult:
return JavaScript("alert({'TEST'})");
the javascript can be run in the client site.

Categories: JQuery | MVC

October 2, 2012
@ 11:46 PM
MVC Techniques with jQuery, JSON, Knockout, and C#


also need check this:



Categories: JQuery | MVC

My Ajax call replace a dropdown box,  then call
$('select').each(function () {

to update the jquery selectBox look and feel again.

but it caused the "setting is undefined: settings.menuTransition" error,

to fixed that need add

            $('select').each(function () {
Before the Ajax Call, so the next time you Initial it .the dropdown will be function..

Categories: JQuery

September 16, 2011
@ 12:44 AM
check the JQuery Ajax:
type: "POST",
url: this.url,
data: form_data,
beforeSend: function() {
error: function() {
$('#status').text('Update failed—try again.').slideDown('slow');
success: function() {
$('#status').text('Update successful!');
complete: function() {
setTimeout(function() {
}, 3000);

to get the from data:
var form_data = $("form").serialize();
var form_data_array = $("form").serializeArray();
a simple example:
$(document).ready(function() {
$('#submit').click(function () {
var name = $('.uname').val();
var data = 'uname=' + name;
data: data,
success: function (html) {
return false;

and MVC3 Ajax
@using (Ajax.BeginForm(       
new AjaxOptions {
 UpdateTargetId = "modal-dialog",
OnBegin = "Dialog.Updating()",
OnSuccess = "Dialog.Update({title:'Select Friends'})"
})) {
… <input type="submit" value="Next" />

Categories: JQuery | MVC