Wednesday, July 30, 2014

Step by Step how to add a RESTful Web API to an MVC 4 Application in 10 minutes

Want to know how to add a RESTful Web API to your MVC 4 Application? Here we'll add a Web API  supporting all C.R.U.D. (Create Retrieve Update Delete) functionality, using ApiControllers. Here we use the Visual Studio 2012 Web API template for creating Controllers inheriting from the ApiController class instead of inheriting from the Controller class.
The ApiControllers are meant to return data instead of Views, serializing this data into the format requested by the client, thus providing a RESTful API.
Common Controllers can also full that requests, but you have to code much more if you want to make a RESTful application using just regular Controllers.
The API we are building will be based on the REST (REpresentational State Transfer) architecture, created by Dr. Fielding by 2000. Our API will just check the HTTP request & determine whether it intends to   :

1) CREATE an item :     HTTP "POST" request
2) RETRIEVE  an item : HTTP "GET" request
3) UPDATE  an item :    HTTP "PUT" request
4) DELETE  an item :     HTTP "DELETE" request

Asp.Net MVC 4 supports RESTful Web APIs, and helps you creating them automatically by means of a strongly typed Controller that inherits from the ApiController class.
You can create both an entire Web API MVC Application, or add a Web API to an existing MVC app.
This way, your application could serve several different web clients, including mobile, tablets, it doesn't matter the client technology because the API will return JSON or XML data to be parsed at client side.
We'll want to create such a RESTful Web API with CRUD functionality , in 10 minutes, showing the XML returned data as follows:



First, add a folder to hold the Web API controllers:
Select API Controller with read-write actions:


Tell Visual Studio which Model to use, and which Data Context:

In this example, we use the following Model:

After the ApiController is built , we have the following CRUD (Create Retrieve Update Delete) Actions in our ApiController: there are two Actions to handle HTTP GET requests:

That was to Retrieve the data. For Create a new record, the API uses the HTTP POST method:


In order to UPDATE a record, the Web API handles HTTP PUT verbs:


And to REMOVE a record, uses an HTTP DELETE verb:

Run the application. If you get the following error:

Fix it by desabling the Proxy creation at the constructor of the ApiController:


Browse again and get the required record:



That's all!! 
In this tutorial we've learn how to add a RESTful Web API to a MVC 4 Application, supporting all CRUD (Create Retrieve Update Delete) C R U D functionality.  

Happy programming.....
       By Carmel Shvartzman
כתב: כרמל שוורצמן

Tuesday, July 29, 2014

Step by step how to use the Carousel Widget of the Twitter Bootstrap in MVC


How to add a Carousel Component of the Twitter Bootstrap to your MVC app or your web page? Here we exemplify how you can show an outstanding carousel in your website. The Twitter Bootstrap includes many open source plugins and widgets to import to your web page, with proved responsiveness and elegant design, which adapt themselves to the mobile or tablet device when size decreases.

In this tutorial we'll make use of the JavaScript Carousel Plugin of the Bootstrap.

We suppose you have installed the Twitter Bootstrap in your MVC app. If you don't, learn  in this tutorial how to setup.

In just 5 minutes we'll build a responsive web page using the  Carousel Widget  Component of the Twitter Bootstrap :




The Twitter Bootstrap can be reached & downloaded from the Bootstrap official site : Bootstrap :




Create an HTML web page or an MVC View, but make sure to load the CSS and the .js jQuery scripts in the page:





TWITTER BOOTSTRAP  CAROUSEL Widget 


Go to the Bootstrap and copy the  Carousel Widget  markup : 


Then paste it inside your MVC View or your HTML page, making the necessary changes to customize the Carousel to your App. I remarked in red the essential properties to declare , in order to transform the <div>s into a Carousel. You can COPY-PASTE this customized Carousel markup :

<div id="carousel" class="carousel slide col-lg-4" data-interval="2000" data-ride="carousel">                <ol class="carousel-indicators">                    <li data-target="#carousel" data-slide-to="0" class="active"></li>                    <li data-target="#carousel" data-slide-to="1"></li>                    <li data-target="#carousel" data-slide-to="2"></li>                    <li data-target="#carousel" data-slide-to="3"></li>                    <li data-target="#carousel" data-slide-to="4"></li>                    <li data-target="#carousel" data-slide-to="5"></li>                </ol>                <div class="carousel-inner" >                    <div class="item active">                        <img src="Images/Bulbophyllum.jpg" alt="Bulbophyllum" />                        <div class="carousel-caption">                            <b>Bulbophyllum</b>                        </div>                    </div>                    <div class="item">                        <img src="Images/Cattleya.jpg" alt="Cattleya" />                        <div class="carousel-caption">                            <b>Cattleya</b>                        </div>                    </div>                                    </div>                <a class="left carousel-control" href="#carousel" role="button" data-slide="prev">                    <span class="glyphicon glyphicon-chevron-left"></span>                </a>                <a class="right carousel-control" href="#carousel" role="button" data-slide="next">                    <span class="glyphicon glyphicon-chevron-right"></span>                </a>            </div>



As you see, we declare a "carousel slide" class, and define a data-interval in milliseconds, and a data-ride to start the animation on page load. Then we define an <OL> "carousel-indicator" , which exactly the number of slides in the carousel-inner <div>. Finally, we create the Carousel controls as follows:




If the size of the pictures is very varied, you can set it in your CSS as follows:

img {    width:390px !important;    height:360px !important;    }



Save & refresh the web page :





And of course, the Carousel is perfectly responsive in mobiles and tablets:





That's all!!  In this tutorial we've learned how to use the Carousel Widget   Component of the Twitter Bootstrap as a Menu. 
Happy programming.....
        By Carmel Schvartzman

כתב: כרמל שוורצמן







Monday, July 28, 2014

Step by step how to create a Dropdown with the Twitter Bootstrap


In this post we'll learn how to create a Dropdown with the Twitter Bootstrap. We'll customize the dropdown component to act as a select list and not as a menu, the default behavior of the Twitter Bootstrap Dropdown. The Twitter Bootstrap includes many widgets for you to bring to your web page with proved responsiveness and elegant design
We will need here the Twitter Bootstrap : learn  in this tutorial how to install it in just 2 minutes

In just 5 minutes we'll build a responsive webpage using a customized Dropdown Component from the Twitter Bootstrap :




The Twitter Bootstrap can be downloaded from the Bootstrap site : Bootstrap :




Create an MVC View, and make sure to load the CSS and the .js jQuery scripts in the page:






TWITTER BOOTSTRAP Dropdown 


Go to the Bootstrap and copy the Dropdown  markup : 


Then paste it inside your MVC View:

 <div class="dropdown">                    <a id="dropdown-btn" class="btn btn-default" role="button" data-toggle="dropdown" href="#">                        Select an Item <span class="caret"></span>                    </a>                    <ul id="menu1" class="dropdown-menu" role="menu" aria-labelledby="dropdown-btn">                        <li><a href="#">Value #1</a></li>                        <li><a href="#">Value #2</a></li>                        <li class="divider"></li>                        <li><a href="#">Value #3</a></li>                        <li><a href="#bottom">Value #4</a></li>                    </ul>                </div>


And also add the following jQuery code to fetch the selected value:


<script>    $(function () {    $(".dropdown-menu li").click(function () {        $("#dropdown-btn").text("You selected " + $(this).text());    });    })
</script>



Save & refresh the web page, and select an item from the dropdownlist :








That's all!!  In this tutorial we've learned how to create a Dropdown with the Twitter Bootstrap. There are more components, and there will be many more in the future. This tutorial does not intends to survey all components, but give you the tools for you to continue exploring them on your own.
Happy programming.....
        By Carmel Schvartzman
כתב: כרמל שוורצמן







Sunday, July 27, 2014

Step by step how to create a Rich Form with the Twitter Bootstrap Widgets in MVC


Using the Twitter Bootstrap you can create elegant & responsive Rich Forms in MVC . All that's required is to bind the MVC Model to the open source Twitter Bootstrap widgets. 

The Twitter Bootstrap includes a lot of wigets and plugins to bring to your web page, with excellent responsiveness and elegant design, becoming the more widely used and popular CSS3 open source framework.

First of all, we'll need the Twitter Bootstrap CSS3 and JavaScript files. You can have  the Twitter Bootstrap installed in your MVC app in a few steps, as described   in this tutorial .

In just 15 minutes we'll build a responsive Rich Form made up of Widgets from the Twitter Bootstrap :




The Twitter Bootstrap can be reached  at the Bootstrap official website : Bootstrap :




First add to your web page the CSS and the .js jQuery files :







BUILDING A TWITTER BOOTSTRAP RICH FORM


In order to apply the Twitter Bootstrap to all TextBoxes in your application, the coolest way is to modify the Display and Editor Templates, located at "Views/Shared/DisplayTemplates/<type>.cshtml"  or "Views/Shared/EditorTemplates/<type>.cshtml" .
You can define custom templates overriding the default templates by creating your custom editor or display templates into the path above.
In our example, we modify the Editor Template to attach an Twitter Bootstrap class:



@model string

@Html.TextBox(@"",Model != null ? Model.Trim() : String.Empty  , new { @class="form-control" } )




We'll build a Rich Form for a Message creation, therefore we'll add some Data Annotations to our Model, as follows:





public class Message
    {
        public int ID { get; set; }
        [Required]
        public string To { get; set; }
        [Required]        
        public string Sender { get; set; }
        [Required(AllowEmptyStrings = false)]
        [StringLength(100, MinimumLength = 5)]
        public string Title { get; set; }
        public string Contents { get; set; }
    }


As you see, we just set some fields as "Required", and one of them will have a minimal length.
Then scaffold a strongly typed View for the Create Action method:



And customize it adding the Twitter Bootstrap classes as follows:
1) Add a Bootstrap Panel to holds the Form:

<div class="panel panel-default">
    <div class="panel-heading">
        <h2 class="text-muted">Create New Message</h2>
    </div>
    <div class="panel-body text-muted">

2) Arrange the Form controls according to the Bootstrap Layout Grid (12 columns) using the classes:

<div class="col-xs-6">

3) Locate the Validation Messages together at the end of the Form, and add them the Bootstrap class "new { @class = "alert alert-warning" }":

 <p>@Html.ValidationMessageFor(model => model.To, 
                                "Please enter the Email where to send the message", new { @class = "alert alert-warning" })
         @Html.ValidationMessageFor(model => model.Sender, 
                                "The Sender field is mandatory", new { @class = "alert alert-warning" })
                        </p>
                        <br />
    <p>@Html.ValidationMessageFor(model => model.Title, 
                                "Do you want to send a message without Title?", new { @class = "alert alert-warning" })
          @Html.ValidationMessageFor(model => model.Contents, 
                                null, new { @class = "alert alert-warning" })
                        </p>

4) Customize the Send button:

 <div class="btn-msg col-md-12">
                            <input class="btn btn-default" type="submit" value="Send Message" /><br />
                            <br />
  </div>

5) Add a DropDownList binded to some field as follows:

<div class="col-xs-6">
                        <div class="editor-label">
                            @Html.LabelFor(model => model.To)
                        </div>
                        <div class="editor-field">                            
                            @Html.DropDownListFor(model => model.To, null, null, 
                                   new { @class = "form-control"})
                        </div>
                    </div>



Because the DropDownList  received a "null" parameter as data source, the MVC will automatically  search for a "model.To" List<> at the Model. We add also the Bootstrap class to customize the control. Notice that we wrote "@class", because "class" is a reserved word of C#, and we shouldn't use it.



6) Then we add an Email TextBox, but instead of declaring it as Email at the Model using Data Annotations, we declare it here, to prove that it's possible but not advisable (business logic MUST be placed at the Model) :

<div class="col-xs-6">
                        <div class="editor-label">
                            @Html.LabelFor(model => model.Sender)
                        </div>
                        <div class="editor-field">
                            @Html.TextBox("Sender", "", new { @class = "form-control", 
                                    placeholder = "Type your email here", type = "email" })

                        </div>
                    </div>




7) Then we add two more fields:
<div class="col-xs-12">
                        <div class="editor-label">
                            @Html.LabelFor(model => model.Title)
                        </div>
                        <div class="editor-field">
                            @Html.TextBox("Title", null, new { @class = "form-control" })

                        </div>
                    </div>
                    <div class="col-xs-12">
                        <div class="editor-label">
                            @Html.LabelFor(model => model.Contents)

                        </div>
                        <div class="editor-field">
                            @Html.TextArea("Contents", "", new { @class = "form-control", 
                                    placeholder = "Here goes your message text" })

                        </div>
                    </div>

8) We add also the Bootstrap Checkbox:

<div class="col-xs-4">

                        <div class="checkbox">
                            <label>
                                <input type="checkbox" value="">
                                Checkbox one
                            </label>
                        </div>
                        <div class="checkbox">
                            <label>
                                <input type="checkbox" value="">
                                Checkbox two
                            </label>
                        </div>
                        <div class="checkbox disabled">
                            <label>
                                <input type="checkbox" value="" disabled>
                                Checkbox three is disabled
                            </label>
                        </div>
                    </div>




9) And finally the Bootstrap RadioButtons:

<div class="radio">
                            <label>
                                <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked>
                                Radio button one
                            </label>
                        </div>
                        <div class="radio">
                            <label>
                                <input type="radio" name="optionsRadios" id="optionsRadios2" value="option2">
                                Radio button two
                            </label>
                        </div>
                        <div class="radio disabled">
                            <label>
                                <input type="radio" name="optionsRadios" id="optionsRadios3" value="option3" disabled>
                                Radio button three is disabled
                            </label>
                        </div>




10) I also customized the "Back to list" link:


<div>
    @Html.ActionLink("Back to List", "Index", null, new { @class = "btn btn-default" })
</div>

11) MAKE SURE you brought the jquery.unobtrusive and the jquery.validate javascript files:

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

The above Bootstrap markup is available at the Twitter Bootstrap website. You could also go to the Bootstrap website and copy the Widgets markup, then paste it inside your MVC View:





Then , add to the Controller the code to populate the Select List:




public ActionResult Create()
        {
            SortedDictionary<int, string> dict = new SortedDictionary<int, string>() {
                { 0, "The Professor" }, 
                { 1, "Philip J. Fry" }, 
                { 2, "Bender Rodriguez" }, 
                { 3, "Turanga Leela" }, 
                { 4, "Nibbler" } 
            };

            List<SelectListItem> options = new List<SelectListItem>();
            //  important! : "Value" must be "" !!!! (else, the "Required" data annotation won't work) : 
            options.Add(new SelectListItem { Value = "", Text = "Select an Email from the List" });
            foreach (var option in dict)
            {
                options.Add(new SelectListItem { Value = option.Key.ToString(), Text = option.Value });
            }
            ViewBag.To = options;
            return View();
        }

Save & refresh the web page. If you try to send the Web Form with the empty fields, you will get the Bootstrap Alerts warning you:


As you fill the fields, the Alerts go and disappear:



Finally, you will succeed sending the Form, and will be redirected to the Messages list:





That's all!!  Here we've learned how to create a Rich Form with the Twitter Bootstrap Widgets in MVC .

Happy programming....
        By Carmel Schvartzman
עריכה: כרמל שוורצמן