29 May 2012

Customer KnockoutJS Validation

This article is the second on KnockoutJS series I am writing.
The first article was introductory: Customer KnockoutJS and MVC demo using JSON

Now I am going to focus on KnockoutJS and validation. I am going to use a KnockoutJS Plugin for model and property validation that is named Knockout Validation. You can download it from here.

The Asp.Net MVC Controller have the actions to Get and Add a customer. This example has a new customer property: the country.
This property allows to add an input type select to KnockoutJS and validation.
namespace KnockoutDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "";

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Get(int customerID)
        {
            // Get the customer ...
            Customer customer = new Customer {CustomerID = customerID, 
                                              FirstName = "John", 
                                              LastName = "Doe", 
                                              IsMale = true, 
                                              CountryID = 1 };
            return Json(customer);
        }

        [HttpPost]
        public JsonResult Add(Customer customer)
        {
            // Save the customer ...

            // return status message 
            var message = string.Format("Customer: {0} {1} Added. IsMale: {2} Age:{3}  CountryID: {4} ",
                                        customer.FirstName, customer.LastName, customer.IsMale.ToString(), 
                                        customer.Age.ToString(), customer.CountryID.ToString());
            return Json(message);
        }

    }
}

The Asp.Net MVC model is the customer with the new property:
 namespace KnockoutDemo.Models
{
    public class Customer
    {

        public int CustomerID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool IsMale { get; set; }
        public int Age { get; set; }
        public int CountryID { get; set; }
    }
}


The Asp.Net MVC Layout includes the new knockout validation plugin:
       
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/knockout.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/json2.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/knockout.validation.js")" type="text/javascript"></script>
</head>
<body>
    <div class="page">
        <header>
            <div id="title">
                <h1>Knockout Demo</h1>
            </div>
            <div>&nbsp;</div>
        </header>
        <div>&nbsp;</div>
        <div>&nbsp;</div>
        <section id="main">
            @RenderBody()
        </section>
        <footer>
        </footer>
    </div>
</body>
</html>
And the Asp.Net MVC view has the KnockoutJS and validation specifics:
@{
    ViewBag.Title = "Add Customer";
}



@ViewBag.Message

Customer Number:

First Name: Last Name: Age: Male Country:


The KnockoutJS now has a observableArray of countries in the VewModel, that is bind to the country select.
Note the data-bind oprtions of the select:
- options: controls what options should appear in a drop-down lis
- optionsValue: The name of the ViewModel property to bind to the option value
- optionsText: The name of the ViewModel property to bind to the option text
- value: The name of the ViewModel property to bind to the selected value
- optionsCaption: The option that is used to make the user select a value on the select list

There is also the validation plugin specifics in the VewModel declaration:
- The extend is used to extend the observables with the validation rules. (you can read about all of them here)
In the example I am using the required  (required: true) and number (number: true) validation rules.
- validatedObservable in the view model declaration
- isValid() - Before saving the data validate that the model is valid
- validation.init - Used to configure the validation engine

In the example the invalid inputs are painted in red, that is where the css class is used by the validation.

07 May 2012

Customer KnockoutJS and MVC demo using JSON

After reading about KnockoutJS I have decided to create a simple demo using JSON to comunicate with the web server.
The application retrieves a Customer from an ASP.Net MVC Action and sends it to be saved.

The KnockoutJS is a JavaScript Model View ViewModel (MVVM) framework.
The View Model object contains properties which values are specified as ko.observable(). Knockout will automatically updates the UI when the view model changes.
KnockoutJS has a declarative binding syntax where the HTML view elements are bind with our view model object. Knockout uses the "data-bind" attribute in the HTML elements for the data binding.

To learn the basics goto the KnockoutJS site by pressing here

Pr-requisites:
1) KnockoutJS
2) json2.js - for json parsing
3) ASP.NET MVC
4) jQuery

The Asp.Net MVC Controller have the actions to Get and Add a customer.

namespace KnockoutDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "";

            return View();
        }


        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Get(int customerID)
        {
            // Get the customer ...
            Customer customer = new Customer {CustomerID = customerID, FirstName = "John", LastName = "Doe", IsMale = true };

            return Json(customer);
        }


        [HttpPost]
        public JsonResult Add(Customer customer)
        {
            // Save the customer ...

            // return status message 
            var message = "Customer: " + customer.FirstName + " " + customer.LastName + " Added.";
            message += " IsMale: " + customer.IsMale.ToString();
            return Json(message);
        }

    }
}

The Asp.Net MVC model is the customer:
    public class Customer
    {
        public int CustomerID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool IsMale { get; set; }
    }


The Asp.Net MVC Layout:
    
 <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/knockout.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/json2.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/knockout.validation.js")" type="text/javascript"></script>
</head>
<body>
    <div class="page">
        <header>
            <div id="title">
                <h1>Knockout Demo</h1>
            </div>
            <div>&nbsp;</div>
        </header>
        <div>&nbsp;</div>
        <div>&nbsp;</div>
        <section id="main">
            @RenderBody()
        </section>
        <footer>
        </footer>
    </div>
</body>
</html>



And finally the Asp.Net MVC view has the KnockoutJS specifics:
@{
    ViewBag.Title = "Add Customer";
}

<h2>
@ViewBag.Message</h2>
<form action="" method="post">
<b>Customer Number: </b> <span data-bind="text: CustomerID"></span><br />
<br />
<b>First Name: </b><input data-bind="value: FirstName" style="width: 200px;" type="text" /> <br />
<br />
<b>Last Name: </b><input data-bind="value: LastName" style="width: 200px;" type="text" /> <br />
<br />
<input data-bind="checked: IsMale" type="checkbox" /><b>Male</b><br />
<br />
<input data-bind="click: KnockoutDemoNamespace.addCustomer" type="button" value="Add Customer" /><br />
<div id="message">
</div>
</form>


The KnockoutJS has the following specifics:
1) View Model object: customerViewModel
2) HTML View: The HTML from the page with the KnockoutJS specific attributes for data binding
The demo performs a data bind with a span, and the input types text, checkbox and button.
Note that the "data-bind" has the html element attribute to be affected and the View Model property associated.
3) View Model activation: ko.applyBindings(viewModel);

03 May 2012

Error deleting a file: Could not find this item. This is no longer located in

When I was trying to delete a file I got a strange error:
      "Could not find this item. This is no longer located in..."

After some investigation I found the following solution:
1) Open a command prompt
2) Go to the folder where is the located the problematic file:
   cd c:\temp
3) Type the command:
                   dir /x
4) Find the 8.3 filename
5) Delete the file using the command:
    del filenam~1.txt

And bingo...the file is deleted !