Showing posts with label DropDownList. Show all posts
Showing posts with label DropDownList. Show all posts

Tuesday, July 28, 2015

Bootstrap Tutorial Lesson 3 - Navbars with DropDownLists

This is the Step by step Bootstrap Tutorial Lesson 3 - Navbars with DropDownLists
In this Bootstrap tutorial for Beginners we exemplify the use of Navbars, including dropdownlist toggle buttons , and a Search Form. This is for use on all kind of Mobile devices screens  : iPhones, iPads, small screens PCs, Tablets, Nexus Galaxy, desktops computers, and so on...
Building Responsive layouts is very important for the Mobile First development  approach.

Bootstrap Tutorial Lesson 3 - Navbars with DropDownLists



And this is how it looks in Ripple Mobile Emulator, in Nexus Galaxy display:    
Bootstrap Tutorial Lesson 3 - Navbars with DropDownLists    1





Bootstrap Tutorial Lesson 3 - Navbars with DropDownLists


For this example we'll be working with a Bootstrap template downloaded from www.initializr.com/ , as is explained in the following Tutorial about Bootstrap Templates. From this template, we leave the Head untouched, to keep the references to jQuery and the Bootstrap files, and only delete the body contents.
Also, and because we'll also use a Mobile Emulator, please read this short tutorial on installing the FREE Ripple Emulator.

However, if you begin coding a HTML5 file from scratch, just add the following references to the Head :

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

You can download the complete app from the following GitHub repository:

1) Building the Navbar:


First step to build a Navbar is to define a <header> HTML5 element with the Bootstrap class "navbar navbar-default navbar-fixed-top" and the Role = Navigation.
Inside it we set a class="navbar-header" holding a Button which will open the Navbar in mobile devices:

Bootstrap Tutorial Lesson 3 - Navbars with DropDownLists   2

As you see , the button target is the id or the class of a <nav> HTML5 element , initially COLLAPSED :  data-target=".my-navbar-collapse" .
Also, we add 3 "<span class="icon-bar"></span>" in order to draw a button to open the Navbar:


Bootstrap Tutorial Lesson 3 - Navbars with DropDownLists    3

Inside the collapsed  class="navbar-collapse collapse "  <nav>, we insert a  class="nav navbar-nav" <ul> to hold all menu links :

Bootstrap Tutorial Lesson 3 - Navbars with DropDownLists   4


2) Adding a DropDownList to the Navbar:



Inside one of the <li>, defined as  class="dropdown" , we insert
1 - a link button <a> to open the dropdownlist
2 - a <ul> representing the dropdown elements:

Bootstrap Tutorial Lesson 3 - Navbars with DropDownLists  5

The button has to bore the following class definitions:  class="dropdown-toggle" data-toggle="dropdown" href="#"  :
Here you have another example of dropdownlist added to the Navbar:


Bootstrap Tutorial Lesson 3 - Navbars with DropDownLists   6





3) Adding a Form to the Navbar:

To add a Form, just include it inside the <nav> element, with a class definition as follows:
<form class="navbar-form navbar-right" role="form">
Bootstrap Tutorial Lesson 3 - Navbars


That's all.
For the sake of the example, we add some text inside a Bootstrap jumbotron, as follows:

Bootstrap Tutorial Lesson 3




And the Navbar will be showed this way:

1-phones : 

Bootstrap Tutorial


2-tablets and medium desktops:

Bootstrap

Tutorial Lesson 3 - Navbars with DropDownLists

Lesson 3 - Navbars with DropDownLists





3-larger desktops:


Navbars with DropDownLists





      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, April 27, 2014

Step by Step how to create a Cascading DropDownList with Ajax functionality

        By Carmel Shvartzman


In this tutorial we'll learn how to create two Cascading DropDownLists with Ajax functionality. The  two Cascading DropDownLists will update its items dynamically Ajax-loading data from database, according to the user's selections.

We'll design a web site using a free CSS Template, as explained in a former tutorial,  and a JQuery UI Theme that we imported in this tutorial. They are short step by step begginer's guides, so if you like the look-and-feel of this web site, follow those 10 minutes tutorials to make this same site.

We'll want to create two Cascading DropDownLists with Ajax functionality , showing as follows:

The <select> tags will be loaded with data from the following related entities:


First, create a new Controller and create a Repository instance (provided you have one):


Add a new View for the Index Action method, and create two <select> as follows:

<div class="ui-widget-content ui-corner-all divselect">
    <div class="float-left">
        Select a Blog Post
        <br />
        <select id="Posts">
            <option value="-1">Select a Post</option>
        </select>
    </div>
    <div class="float-right">
        Select a Post Comment<br />
        <select id="Comments">
            <option value="-1">Select a Comment</option>
        </select>
    </div>
    <div id="txtComment" class="ui-widget-content ui-corner-all divselect float-left"></div>
</div>

Notice we're using the JQueryUI theme CSS classes.
Now add a <script> and an Ajax $.getJSON() call which executes right after the HTML document is loaded. This call will populate the FIRST <select>  control:


<script>$(function () {
    $.getJSON("CascadingDDL/Blogs/", function (data) {
        var list = "<option value='-1'>Select a Post</option>";
        $.each(data, function (i, post) {
            list += "<option value='" + post.Value + "'>" + post.Text + "</option>";
        });
        $("#Posts").html(list);
    });

The function makes a HTTP_GET call to the following Action method, which returns all the Blog posts in JSON notation:


public ActionResult Blogs()
        {
            List<Blog> posts = Rep.RetrieveBlog(null).ToList();
            if (HttpContext.Request.IsAjaxRequest())
            {
                SelectList select = new SelectList(posts, "BlogID", "Title");
                return Json(select, JsonRequestBehavior.AllowGet);
            }
            return View(posts);
        }

This Action method uses the RetrieveBlog method on the Repository:

       public IEnumerable<Blog> RetrieveBlog(int? Id)
        {
            List<Blog> list = new List<Blog>();
            if (Id.HasValue)
            {
                list.Add(Context.Blogs.Find(Id));
            }
            else
            {
                list = Context.Blogs.ToList();
            }
            return list;
        }

It's a generic method which works with or without a parameter.
Next, add an event handler for the 1st <select> CHANGE event at the <script>:


 $("#Posts").change(function () {
        var PostId = $("#Posts > option:selected").attr("value");
        $.getJSON("CascadingDDL/Comments/" + PostId, function (data) {
            var list = "<option value='-1'>Select a Comment</option>";
            $.each(data, function (k, comment) {
                list += "<option value='" + comment.Value + "'>" + comment.Text + "</option>";
            });
            $("#Comments").html(list);
        });
    });

This sends an Ajax HTTP_GET request to populate the 2nd <select> with the data corresponding to the SELECTED value at the 1st <select> control. This $.getJSON calls another Action method :



 public ActionResult Comments(int? Id)
        {
            List<Comment> comments = Rep.RetrieveBlogComments(Id).ToList();
            if (HttpContext.Request.IsAjaxRequest())
            {
                SelectList select = new SelectList(comments, "CommentID", "Title");
                return Json(select, JsonRequestBehavior.AllowGet);
            }
            return View(comments);
        }

This method uses another Repository function as follows:

 public IEnumerable<Comment> RetrieveBlogComments(int? Id)
        {
            List<Comment> list = new List<Comment>();
            if (Id.HasValue)
            {
                list = Context.Comments.Where(c => c.BlogID == Id).ToList();
            }
            else
            {
                list = Context.Comments.ToList();
            }
            return list;
        }


This fetchs only the Comments corresponding to the selected Blog post.
Finally, append a last $.ajax HTTP_POST function to the <script>, in order to get the text of the selected Comment:

$("#Comments").change(function () {
        var Id = $("#Comments > option:selected").attr("value");
        if (Id >= 0) {
            $.ajax("CascadingDDL/CommentText/", {
                data: { "CommentId": Id }, type: "POST", success: function (txt) {
                    $("#txtComment").html("<i>" + txt + "</i>");
                }
            });
        }
    });

This $.ajax calls the following Action method:


 public JsonResult CommentText(int? CommentId)
        {
            if (HttpContext.Request.IsAjaxRequest())
            {
                string comment = Rep.RetrieveComment(CommentId).Text;
                return Json(comment);
            }
            return Json("");
        }

This Action method uses a Repository function to fetch the Comment's text::


 public Comment RetrieveComment(int? Id)
        {
            Comment comment = null;
            if (Id.HasValue)
            {
                comment = Context.Comments.Where(c => c.CommentID == Id).FirstOrDefault();
            }          
            return comment;
        }
Build and run the app:


When the user selects a Post, the list of Comments is refreshed:



And when a Comment is selected, its text is Ajax displayed below:



That's all!! 
In this tutorial we've learn how to create two Cascading DropDownLists with Ajax functionality.  

Happy programming.....


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

Monday, February 10, 2014

Step By Step How to create a DropDownList HTML Helper loaded from Database

        By Carmel Schvartzman
In this tutorial we'll learn how to create a dynamic DropDownList  HTML Helper in an MVC View  in ASP.NET MVC 4. This DropDownList will expose just a few items dynamically loaded from database and sent by the Action method on the web server.

An Html Helper is a class designed for rendering HTML controls to the Views. It supports several extension methods representing the different controls such as forms, textboxes, labels, dropdownlists, routelinks ( "< a >" ) , actionlinks ( "< a >" ) ,textareas, passwords, listboxes, checkboxes, radiobuttons, hidden fields, editors, and validation code.

We'll want to add a  DropDownList to the web page, as follows:


To use the HTML Helpers we must create our own View, so first let's create a new Controller called "NewViewController", and then add a View to the Index Action method. So right click over the Controllers folder, and add a new Controller:



Name it "NewViewController", and select the template "Empty MVC Controller":


Open the Controller file and find the "Index" Action method:



Right click on it and select the option "Add View":


On the dialog, let the name be "Index", select the "ASPX" View engine, and choose a master page:

The HTML Helper we'll learn about is the DropDownList control. For the other HTML Helpers, refer to the "Categories" Menu in the top-right place in this Blog. We'll use the Entity Framework Data Model and the Repository we created in a previous tutorial .  The repository exposes two Entities: Blog and Comment, with a one to many relationship between them. Open the View we just created, and type the TempData["message"] in order to display a message to the user:




Create the Form object taking care of its tags:


Also, add a button in order to submit the form:


Now, add the label which will inform the user what is the dropdownlist about:


Next, we'll add the DropDownList named "BlogPost", using an overload of the extension method with the following parameters:



The second parameter being an IEnumerable<SelectedListItem>, we'll leave it empty with a "null" value , to force the MVC framework to search the ViewBag (and therefore the ViewDataDictionary, because the ViewBag is just a wrapper of the ViewData)  for a key named "BlogPost" as the first argument tells, containing a SelectList of SelectedListItems, which soon we'll add to the Index Action method:



The third parameter is the text to display on the DropDownList , and the fourth is an anonymous object representing the CSS style:





Now for the code in the Action method, find the "Index" in the Controller, and add the code to populate the dropdownlist:



We just instantiate our Repository, and populate the SelectList with a Linq query retrieving the posts. Also, we set the Key and the Text for the SelectList, with the names of the properties we use as Key/Value, in this case, we use the "BlogID" and the "Title" properties.
Now build your application and browse to the "/NewView/Index" (or just "/NewView") web page:




We got this dropdownlist, and select the post with the Title "Sobralia Altissima" and the key "5":




Now, what happens when we press the Submit button? Let's take a look at the Network tab on the Developer's Tools (F12):


An HTTP POST request has been sent to the web server, containing the Form data , the key = "BlogPost" with the value = "5":



Therefore, we need to create a new Action Method at the "NewView" Controller to handle the HTTP POST request ( AcceptVerbs(HttpVerbs.Post) ), with the same name "Index" ( ActionName("Index") ). So add the following Action method with the "BlogPost" parameter:



Also, we'll use the received value to send a message to the user, via the TempDataDictionary:



Because we have to load the dropdownlist again while this Action method render the View , add to the POST Action method the code to populate again the dropdownlist, this time a little more simple, fetching the data directly through the "Blog" DbSet:



Rebuild the application and select a Blog Post, pressing the Submit button:




This time the user gets a message informing her/him that the selected value was 5:




In this tutorial we've learned how to create a DropDownList exposing items dynamically loaded from database and sent by the Action method on the web server, via the TempDataDictionary and the ViewBag wrapper
That's all!! 
Happy programming.....


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