Sunday, December 4, 2011

Amplify.Request

What is Amplify.Request ?


amplify.request is an abstraction layer that can be used for any kind of request for data. amplify.request sets out to separate the data retrieval and caching mechanisms from data requestors.

Demo Overview  Download

Requesting player list and player details using Amplify.Request.

.JS files


amplify.js
amplify.request.js
amplify.store.js


Amplify calls





HTML View



Amplify Demo



Players list:




   





Player Name:  










References :

http://amplifyjs.com/api/request/

Javascript Knockout

What is Javascript Knockout ?

Knockout is a JavaScript library that makes it easier to create rich, desktop-like user interfaces with JavaScript and HTML, using observers to make your UI automatically stay in sync with an underlying data model. It works particularly well with the MVVM (Model View View Model) pattern.

Demo Overview  Download

A simple scenario - Choose your indian cricket team for the upcoming Australia Serires.

Templating using JS Knockout









HTML View






Players Available :




Selected Players:


















References:
http://knockoutjs.com/

Saturday, November 19, 2011

Link for all materials on MVC from Microsoft



http://msdn.microsoft.com/en-us/library/gg416514(v=vs.98).aspx

Progressively enable the mobile web with MVC4, HTML5 and JQuery Mobile. Here the presentation from Phil Haack, senior program manager, Microsoft.

http://channel9.msdn.com/events/BUILD/BUILD2011/TOOL-803T


Enjoy !!!

Wednesday, November 16, 2011

Populate a Dropdown in MVC

Scenario- How to develop a reusable component to populate all dropdowns in MVC applications.

Design-
Repository class - LookupRepository.cs that will fetch lookup values from DB.
Static Extension class - LookupExtension.cs will have method that will extend Dictionary object and return list of SelectListItems.
Static Helper class - LookupHelper.cs will call the repository, cast the result to list of SelectListItems and build SelectList.

Model class

public class Sample
{
public int Country {get; set;}
public SelectList Countries {get; set;}
}


Controller code

public ActionResult Index()
{
var model = new Sample();
model.Countries = LookupHelper.Countries;
return View(model);
}


Index.chtml code

@model Sample
@Html.DropDownListFor(m => m.Country, Model.Counties, new { @style = "width:86%" })


LookupHelper.cs


public static SelectList Counties
{
get
{
return new SelectList(_lookupRepository.Countries.ToSelectListItems(), "Text", "Value");
}
}

LookupExtensions

public static IEnumerable ToSelectListItems(this IDictionary items, string selected = "1")
{
return items.Select(k =>
new SelectListItem
{
Selected = (k.Value == selected),
Text = k.Key,
Value = k.Value
});
}

Review on Telerik ASP.NET MVC Extensions

We used Telerik ASP.NET MVC Extensions GPL 2.0 in our last project extensively. Beside some initial challenges, we able to successfully delivered the project on time. Some of the coolest controls that we used are: Grid, TabStrip, PanelBar, Window, Numeric, Upload.

The features that I liked the most are:
1. In line editing feature of Grid like ASP.NET Grid control.
2. Client side events like OnLoad, OnEdit, OnDelete etc. supported by Telerik controls.
3. Row level formatting in the Grid.
4. Client/Server Template for bound columns.
5. Upload control supports uploading multiple files.

Challenges-
1. No proper support for Dropdown in inline editing Grid.

Reference : http://demos.telerik.com/aspnet-mvc/

ASP.NET MVC 4 Developer Preview features



Enhancements to Default Project Templates - The Web Site created using Default Project Template gives more modern look.

Mobile Project Template - This is the most important feature in this release. This helps you to create site specifically for mobile and tablet browsers. This is based on JQuery Mobile - open source for touch optimized UI JQuery Mobile Documenation.

MVC 4 Mobile Features

Display Modes - This feature allows the application to select views depending on the browser i.e. Desktop Browser or Mobile. It supports views like _Layout.chtml for Desktop browser, _Layout.mobile.chtml for mobile browser.

Task support for Async Controller - Async Controller returns an Task. The async Controller actions also support timeout.

Azure SDK - Supports for Windows Azure SDK (Sept 2011 1.5)

Looking forward for next release...

Monday, November 14, 2011

How to render Model validation errors on Ajax Calls in ASP.NET MVC

As we all know that Web Development without Jquery & Ajax is an impractical idea. Most of us use Data Annotations for validation purposes. How these Data Annotatation will work on client side when you have Ajax calls in your application. MVC doesn't take care of firing these validations when Ajax calls are made. The below approach can help you handle this situation.

1. MVC generates a spantag i.e. span class="data-valmsg-for=Field Name" for each field that has Html.ValidationMessageFor() in it's markup.
2. Let controller action validates the model and returns you a Json object with all validation messages back to your Ajax call. This collection will have both the Key i.e. Field Name and the validation message.
3. The Ajax call will loop thru this Array and render this messages in the span of appropriate field element.

Base Controller Code


public JsonResult ValidateModel(string status = "")
{
bool isValid = ModelState.IsValid;

return Json(new
{
Valid = isValid,
NewId = 0,
Errors = GetErrorsFromModelState(),
Status = !string.IsNullOrWhiteSpace(status) ?
status :
isValid ? "Success" : "Failure"
});
}

public Dictionary GetErrorsFromModelState()
{
var errors = new Dictionary();

foreach (var key in ModelState.Keys)
{
// Only send the errors to the client.
if (ModelState[key].Errors.Count > 0)
{
errors[key] = ModelState[key].Errors;
}
}

return errors;
}

public void ClearValidationError()
{
foreach (var key in ModelState.Keys)
{
if (ModelState[key].Errors.Count > 0)
{
ModelState[key].Errors.Clear();
}
}
}


Application Contoller Code

public ActionResult Edit(TemplateViewModel model)
{
bool returnStatus = false;
var id = SaveNewTemplate(model);
returnStatus = true;
JsonResult validation = ValidateModel();
return Json(new { success = returnStatus, id = id, message = message, Validation = validation });
}


Cliend side code

$.ajax({
type: "POST",
url: form.attr("action"),
dataType: "json",
async: false,
cache: false,
data: form.serialize(),
success: function (result) {
if (result.success) {
if (result.Validation != null && !result.Validation.Data.Valid) {
$.each(result.Validation.Data.Errors, function (key, value) {
if (value != null) {
var container = $('span[data-valmsg-for="' + key + '"]');
container.removeClass("field-validation-valid").addClass("field-validation-error");
container.html(value[value.length - 1].ErrorMessage);
}
});
}
}
});