Tuesday, September 24, 2013

Using jQuery to Post Data to an ASP.Net Web Forms Web Method via Model Binding

Scenario

I recently ran into a situation where I needed to use AJAX to call back to a traditional ASP.Net Webform's web method in the code behind for a quick lookup. There was a large number of values that were directly related to a model I was using. So, I decided to do this via model binding similarly to how ASP.Net MVC utilizes this same binding techniques for the post data, to keep from having to do the parameter to model translation and save myself some typing.

As a personal preference, I like to use JavaScript Object Notation (JSON) to populate the data being submitted to the server. This is just a personal preference because I feel the code is more readable and I have never been a big fan of string concatenations. I mention this because there is a needed work around for IE 8 or old due to the lack of native support for the JSON object. For more information please see http://blogs.msdn.com/b/ie/archive/2008/09/10/native-json-in-ie8.aspx

The Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.Model
{
public partial class MyFormClass
{
public string Field1 { get; set; }
public string Field2 { get; set; }

}
}
The Form

In the code below you can see I have simplified the form to contain only a couple fields but this is just to condense the code posted. Also notice that that there are three JavaScript files used. jQuery, json2 to accommodate IE8 and older, and the page specific JavaScript file.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="WebApplication1.Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Test</title>
<script src="Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="Scripts/json2.js" type="text/javascript"></script>
<script src="Scripts/MyFormClassJavaScript.js" type="text/javascript"></script>

</head>

<body>

<form id="form1" runat="server">
<div>

Field 1 <asp:TextBox ID="txtField1" runat="server"></asp:TextBox>
<br />
Field 2 <input type="text" id="txtField2" /> <br />
<input type="button" onclick="DoWork()" title="Go" value="Go" />
</div>

</form>

</body>

</html>
The Web Method

In the code behind I have the following web method, as you can see I have a parameter named myFormClass of the same type as the model MyFormClass. This method doesn't have any major logic, just simply takes the submitted value throws it into a list and returns the list as a JSON string.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using WebApplication1.Model;
using System.Web.Script.Serialization;

namespace WebApplication1
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

[WebMethod]
public static string GetList(MyFormClass myFormClass)
{
//Using a list to show how lists can be returned instead of single objects
List myList = new List();

//just as the submitted value to the list, obviously this is where your business logic will be submitted.
myList.Add(myFormClass);

//used JavaScriptSerializer just for down and dirty method, there are better method of doing this.
JavaScriptSerializer jss = new JavaScriptSerializer();
return jss.Serialize(myList);
}
}
}
The JavaScript

As you can see the javascript is just a simple function that uses the jQuery Ajax object to post to the web method. Something that you may not recognize is the data filter that is handling the d object that .Net is adding to the JSON object that I serialized. For more information about this data filter see http://encosia.com/never-worry-about-asp-net-ajaxs-d-again/.

All I am doing with the return data object is looking through the array using the jQuery .each function and displaying in an alert window.

The key piece to notice is the JSON.Stringify function I used to create an object with the same name as the parameter of the web method, in this case myFormClass. The value of this object is another object that has two values named Field1 and Field2 which are set to the corresponding text boxes. These are name are extremely import and must match exactly, it is case sensitive, as the property in my model class.

function DoWork()
{
alert('I fired!');
$.ajax({
type: "POST",
url: "Test.aspx/GetList",
data: JSON.stringify({ myFormClass:
{
Field1: $('#txtField1').val(),
Field2: $('#txtField2').val()
}
}),
contentType: "application/json; charset=utf-8",
dataFilter: function (data) {
// This boils the response string down
// into a proper JavaScript Object().
var msg = eval('(' + data + ')');

// If the response has a ".d" top-level property,
// return what's below that instead.
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
success: function (msg) {
// This will now output the same thing
// across any current version of .NET.
$.each(msg, function (key, data) {
alert('Field1: ' + data.Field1 + ' Field2: ' + data.Field2);
});
},
error:function( jqXHR, textStatus, errorThrown ){
alert(textStatus + " : " + errorThrown);
}
});

}
Conclusion

As you can see this is a really simple example but clearly outlines a quick and easy method to utilize model binding when submitting to a web method from a traditional ASP.Net web form.


*** All Content is provided As Is ***

Wednesday, June 5, 2013

How to properly submit an html form to MVC Action with model binding

Just like a view can submit data to an MVC action so can any external HTML forms and model binding can even be used allow for greater code re-usability of existing actions. This is helpful, for example, when you have a couple other sites that you would like to link back to your MVC site to take advantage existing functionality.

If you are familiar with MVC, you are probably already thinking this makes sense because views are just html. Even the helpers that are used in Razor or other syntax implementation, ultimately render as plain old html. So what are the gotchas and things to watch out for?

There are only a couple things that are extremely important and most of it has to do with the HTML form itself, and not so much on the controller action side of things.

First and most importantly the form must be configured to submit to the proper place and the correct method is being used.  When using the default routing configuration in MVC this would be the url/controller/action so something like http://www.mysite.com/mycontroller/myaction. Also make sure that if the action is decorated with the HttpPost attribute then set the method to "post" and likewise HttpGet attribute would be a form method of "get"

Now that the form will successfully submit to the proper action it is time to look at the input or select tags and make sure they have the proper id and name attributes.  I put the word "and" in bold because the model does not bind correctly if you do not have these both properly defined.  To define these properly make sure both the id and name attributes match the name of the parameter of the action or one of the property names of the model being used as the action parameter. For example if myAction had a parameter name "testParam" and "testParam2" then I would need two inputs with the id and name matching the "testParam" for one and "testParam2" for the other.

Example Form:
<form action="http://mycorrecturl/mycontroller/myaction" method="post">
<input id="testParam" name="testParam" type="text" />
<input id="testParam2" name="textParam2" type="hidden" value="junk" />
<input type="submit" title="Submit" />
</form>


Example Action
[HttpPost]
public ActionResult myAction(string testParam, string testParam2)
{
     //do something here
     return View();
}


There are other concerns that require time invested into understanding with MVC in general, like proper request filtering, authentication and other security concerns to ensure that your site and users are safeguarded. For more information about these topics I recommend reviewing Microsoft's MVC tutorial library at http://www.asp.net/mvc/tutorials as a good starting point.    

Tuesday, May 14, 2013

Why to switch from Android to Windows Phone

Switch to Windows Phone, Why?

I have been debating this myself for many weeks, as I have patiently waiting for my carrier, Verizon Wireless to offer the new phone models.  My main debate has been between the Samsung Galaxy S4 and the Nokia Lumia 928.
 
I am not going to go into the specifics about the hardware or vendor specific software, there are plenty of source for this type of information.  I am going to cover fundamental reasons why now is the time to switch to windows phone. 
 

Less carrier and manufacturer modifications

Windows Phone OS's core functionality is by design protected from manufacturer modifications.   This means while device manufactures and even wireless carriers like to add bloat ware and make other core system modifications to the Android's Open Source OS which can cause instability, battery drain, privacy concerns and additional security wholes.
 

Frequent updates, improved security

 
Unlike Android devices updates are not controlled by the cellular carrier, which from my experience are either up to a year past the current Android version, even then the devices only get one maybe two system updates to the operating system.  This is a major concern from my perspective because it means that any security flaws that are fixed in the newer releases are never going to make it my device unless I root it and void any warranty/support for the devices.
 
With Windows Phone the updates come from Microsoft, not the carrier or device manufacturer. No rooting require, no voiding the warranty or support agreements with the manufacturer or carrier.  These updates have been through the proper testing and Microsoft already has a great focus on security, case in point from the windows OS side is a little thing we like to refer to as "Patch Tuesday's".
 
Now Samsung recently was awarded a government contract for their knox software which is a vendor specific piece of software and again subject to carrier changes. But still good news for newer Samsung devices.
 

App market growing

If you expect to find every title that you had in Android, that is not going to happen.  This is a downside but as windows phone is gaining market share and the non-Microsoft ecosystem developers are discovering the easy of app development and fact that all web developer and windows 8 developer skill set cross all platforms there is a strong army of developers that are bringing new apps to the market every day.  I personally, have a couple apps that I am planning to write. 
 
Microsoft is aware of this as being one of the biggest hurdles to making the switch and they are addressing it as discuss in this Computer World article http://www.computerworld.com/s/article/9237836/Windows_8_app_store_growth_slows
 

#TimeToSwitch Android Application

Microsoft in an effort to make the transition easier has published an app to the Android market its called TimeToSwitch.  This app is designed gather what apps you have installed on your phone, save it and when you switch to windows phone it will help you find the same or similar apps in the windows store.  While the key phase in the last statement is same or similar I think there is room for improvement in this application to display the list of which will be same and which are similar a head of time, but hey this is a great start and much easier than the transition from one android device to another.
 

Easy contact migration

Since this uses the SkyDrive and your windows live account, guess what you want your contacts no biggie, log into http://www.outlook.com and important any contacts that you synced with Google or the other social media sites. 
 

Companion Applications for both Windows Phone and Windows 8

 One of the best features is that many of the applications your purchase (paid or free) for windows phone also have a windows 8 compatible version.  Who doesn't like a buy one get one? 
 

SkyDrive and Office Applications

Everyone windows phone comes with free space on SkyDrive, the Nokia Lumia series is stated as coming with 7gigs free.  This makes it really easy to access files from both your PC and on the via your phone or surface tablet.  Having used similar services like Drop Box for similar functionality in Android this was even simpler to setup and even easier to use.
 

Developer Perspective:


Modern UI (Metro) consistencies

The consistency of live tiles between windows phone, windows 8 is a nice change.  Also makes development and design easier which is great for me as a develop who lacks the skills to create amazing looking UI designs.


Its all just HTML5 (faster development) and JavaScript

That's right!  Web Developers and Windows Developers unite, we can draw on the same skill sets for developing for Web apps, Windows Phone, and Windows 8.  What I really like is that I can leverage any and all of the Web API's that I have built for my MVC sites for consumption in my windows phone apps and Windows 8, allowing me to greater code reusability.
 

You are going to pay me to publish apps, sign me up?

If you read the computer world article you will notice that they talk about pay developers to publish application to spur app market growth, well guess what that was just the extra motivation to get me started several app ideas I have been wanting to write. 
 

*** All Content is provided As Is ***

jQuery.noConflict() you smell like a stinky cheese!

So a little background

I was working on a project implementing a design into a project which included the html, graphics and a few javascript libraries and files. Upon initial investigation everything seem on par with what you would expect from a UI using jQuery and jQuery UI. I ran the provided files in the browser and everything seemed okay, no console errors in the browser debugger. It was using a few jQuery plugins that I have never used before but everything seemed to be displaying correctly except for the adGallery plugin, but I wrote that off to a minor error somewhere in the css or markup, knowing that if all else fails, I could easily implement a different plugin like PikaChoose to maintain the functionality.

Now to fix the adGallery

While integrating the design into the functional site I notice on of the javascript files it used jQuery.noConflict(). I didn't recognize this tag as I had never used it, but the jQuery library is pretty expansive and given no browser debugger error I wrote it off to my own lack of knowledge and moved on to trying to fix the adGallery. In Visual Studio, I reviewed the markup and css and both seemed inline with what the documentation was showing but when I ran it Visual Studio I would get an error stating adGallery is not a supported method or property. I did a little searching and nothing turned up about compatibility issues, so I chalked it up to conflict causing the jQuery library to not compile properly at run time. So I switched the markup, css and library out with PikaChoose and attempted to run in debug again.

Here is the smelly part

Unfortunately the error remained only stating that PikaChoose() is not a supported method or property. Having used this before I knew that it worked. This is when I noticed the jQuery.noConflict() a few lines above it, so on a whim I moved my instantiation code above this line and everything ran okay in debug. So I removed this line of code and a new error came light stating that Method of Property 'msie' was not found or null. Turns out that this error was related an incompatibility between jQuery 1.9.1 and jQuery UI 1.8.11.

So what is jQuery.noConflict() used for?

jQuery.noConflict() relinquished the control of the $ object. This would mean that any errors would not show in the debugger because the $ object would be empty or null. For more information on the proper usuage of jQuery.noConflict() check out the API Documentation at http://api.jquery.com/jQuery.noConflict/

In summary if you ever see jQuery.noConflict() make it is truly being used for its intended purpose.

*** All Content is provided As Is ***

Monday, May 6, 2013

CoAuthoring a new NuGet Package csharp.Extensions

A fellow developer and I have decided to coauthor a NuGet package to help us from having to constantly added the same extension methods to our projects.  This project is called csharp.Extensions.  Available at https://nuget.org/packages/csharp.Extensions/

These extension methods allow for quick expansion of the base csharp types including common functions such as converting a comma separated string into a list, or converting a nullable datetime to a non nullable datetime.  We have not compiled the code based because we encourage you to use them and extend them as necessary.

If there is an extension method missing and you would like to added please let us know.  To use in NuGet Package Manager Console type install-package csharp.Extensions.

I hope this helps save you some time and if you have any questions don't hesitate to ask.

*** All Content is provided As Is ***