Tag Archives: bootstrap

How to write your own HtmlHelper render input text in asp.net mvc and working with Date Range Picker

When I was built a tourist website my client’s like have a date range picker. So I search internet found there is this bootstrap date range picker, I am big fun with bootstrap and this is the frond end css framework I am very confident with it.

You could just write html to your view to display it, but what happen if I need use in multiply place and different projects. So I like customize one HtmlHelper to render it.

For how to figure it out in html,.here is the github links.

https://github.com/dangrossman/bootstrap-daterangepicker

I also have picture show:customizeHtmlHelperRenderDateRange02

This date range pick also allow single date pick, how see the help document, because in here I focus how to make it to a Htmlhelper.

Step1: download it, and you only need the moment.js(this is big, if you worries the speed,use the CDN, why CDN help the speed? this is because when the moment.js also used in another projects online, and it already open, then someone go to your website and click it, then you don’t need download it) and daterangepicker-bs3.css

customizeHtmlHelperRenderDateRange01

For me I used it in my asp.net mvc project, I simple just put it inside my bundle.

Step2: start HtmlHelper to render text input box, this time I like also bind it to my model, so it will just like the existing htmlhelper render input text,but write your own one helper you understand how the HtmlHelper works.

here is the method

public static MvcHtmlString MyOwnTextBoxFor<TModel, TValue>(
     this HtmlHelper htmlHelper,
     Expression<Func<TModel, TValue>> expression,
     string type,
     string title,
     string placeholder,
     bool isRequired,
     bool isAutoFocus,
     object htmlAttributes = null)
        {
            MvcHtmlString html = default(MvcHtmlString);
            Dictionary<string, object> attributesOptions = new Dictionary<string, object>();

            if (htmlAttributes != null)
            {
                var attributes =
                  HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
                foreach (var item in attributes)
                {
                    attr.Add(item.Key, item.Value);
                }
            }

            attr.Add("type", type);
            attr.Add("class", "form-control");
            if (!string.IsNullOrEmpty(title))
            {
                attr.Add("title", title);
            }
            if (!string.IsNullOrEmpty(placeholder))
            {
                attr.Add("placeholder", placeholder);
            }
            if (isAutoFocus)
            {
                attr.Add("autofocus", "autofocus");
            }
            if (isRequired)
            {
                attr.Add("required", "required");
            }

            html = InputExtensions.TextBoxFor(htmlHelper,
                                              expression,
                                              attr);

            return html;
        }

And here is the several over load method, so in the view you have more options

public static MvcHtmlString MyOwnTextBoxFor<TModel, TValue>(
      this HtmlHelper htmlHelper,
      Expression<Func<TModel, TValue>> expression,
      object htmlAttributes = null)
        {
            return MyOwnTextBoxFor(htmlHelper, expression,"text", string.Empty, string.Empty, false, false, htmlAttributes);
        }


        public static MvcHtmlString MyOwnTextBoxFor<TModel, TValue>(
          this HtmlHelper htmlHelper,
          Expression<Func<TModel, TValue>> expression,
          string type,
          object htmlAttributes = null)
        {
            return MyOwnTextBoxFor(htmlHelper, expression, type, string.Empty, string.Empty, false, false, htmlAttributes);
        }


        public static MvcHtmlString MyOwnTextBoxFor<TModel, TValue>(
          this HtmlHelper htmlHelper,
          Expression<Func<TModel, TValue>> expression,
          string title,
          object htmlAttributes = null)
        {
            return MyOwnTextBoxFor(htmlHelper, expression, "text", title, title, false, false, htmlAttributes);
        }

        public static MvcHtmlString MyOwnTextBoxFor<TModel, TValue>(
          this HtmlHelper htmlHelper,
          Expression<Func<TModel, TValue>> expression,
          string type,
          string title,
          object htmlAttributes = null)
        {
            return MyOwnTextBoxFor(htmlHelper, expression, type, title, title, false, false, htmlAttributes);
        }


        public static MvcHtmlString MyOwnTextBoxFor<TModel, TValue>(
          this HtmlHelper htmlHelper,
          Expression<Func<TModel, TValue>> expression,
          string title,
          bool isRequired,
          bool isAutoFocus,
          object htmlAttributes = null)
        {
            return MyOwnTextBoxFor(htmlHelper, expression, "text", title, title, isRequired, isAutoFocus, htmlAttributes);
        }

and in the view simple just use it like this

@Html.MyOwnTextBoxFor(m=>m.StartDate)

For date range pick you need a piece of javascript

@section scripts
{// }//for more option could read the github helper document

actually the input text type could be “text”, “email”, “number”, so make it more useful create a enum hoder it,then for the type replace it with that enum method.

public enum MyInputTypesOption
        {
            text,
            color,
            date,
            datetime,
            email,
            month,
            number,
            password,
            range,
            search,
            tel,
            time,
            url,
            week
        }

After this you need change

//string type, //comment out this
MyInputTypesOption type,//use this

//so for the overload method instead of type "text", could use MyInputTypesOption.text

And in the method this time for the attribute I put it in

Dictionary<string, object> attributesOptions = new Dictionary<string, object>();

that is because in the end there use the

InputExtensions.TextBoxFor(htmlHelper,
                                              expression,
                                              attributesOptions);

the big benefit for this just you don’t need send a anonymous objects, and you could pass the html attributes straight way and with intelligence.

And one thing is important, is the date range need input type is “text”.
to create the string.

Have fun!

Advertisements

build one page app by using bootstrap working with angular.js from begginng–Part2

Since sombody is intrested in this topic, I am going to finish it now.

here it is the structure of your folder

spa_01

Her it is the index.html page:

<!DOCTYPE html>
<html lang=”en” ng-app=”CsbApp”>
<head>
<meta charset=”utf-8″>
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<title>AngularJS Tutorial CSB Test App</title>

<!– Bootstrap –>
<link href=”css/bootstrap.css” rel=”stylesheet”>
<link href=”css/site.css” rel=”stylesheet”>

<!– HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries –>
<!– WARNING: Respond.js doesn’t work if you view the page via file:// –>
<!–[if lt IE 9]>
<script src=”https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js”></script&gt;
<script src=”https://oss.maxcdn.com/respond/1.4.2/respond.min.js”></script&gt;
<![endif]–>
<script src=”http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js”></script&gt;
<script src=”https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.26/angular-route.min.js”></script&gt;
<script src=”js/app.js”></script>
</head>
<body>
<div class=”container”>
<div ng-view></div>
</div>

<!– jQuery (necessary for Bootstrap’s JavaScript plugins) –>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js”></script&gt;
<!– Include all compiled plugins (below), or include individual files as needed –>
<script src=”js/bootstrap.js”></script>
</body>
</html>

then the list.html page is the patrial page will dynamic generate into the ng-view div holder:

<div class=”col-sm-6 col-md-6″ ng-repeat=”item in items” id=”{{item._id}}”>
<div class=”row”>
<div class=”col-sm-3 col-md-3″><img src=”{{item.logo.path_to_file}}” alt=”{{item.display_name}}” class=”img-responsive”></div>
<div class=”col-sm-9 col-md-9″>
<blockquote>
<p><i class=”glyphicon glyphicon-home iconstyle”></i> {{item.address.address1}}, {{item.address.suburb}}, {{item.address.postcode}}, {{item.address.state.name}}, {{item.address.country.name}}</p>
<p><i class=”glyphicon glyphicon-envelope iconstyle”></i> {{item.email}}</p>
<p><i class=”glyphicon glyphicon-phone iconstyle”></i> {{item.phone}}</p>
<p><i ng-show=”item.status==’active'” class=”glyphicon glyphicon-ok iconstyle”></i><i ng-show=”item.status!=’active'” class=”glyphicon glyphicon-remove iconstyle”></i> {{item.status}}</p>
</blockquote>
</div>
</div>
</div>

Last part is you module

var module = angular.module(“CsbApp”, [“ngRoute”]);

module.config(function ($routeProvider) {
$routeProvider.when(“/”, {
controller: “listsController”,
templateUrl: “list.html”
});

$routeProvider.otherwise({ redirectTo: “/” });
});

var listsController = [“$scope”, “$http”, function ($scope, $http) {
var self = this;
$http.defaults.headers.get={“x-device-longitude”:0,”x-device-latitude”:0};

var request = {
method:”GET”,
url:”http://api.muulla.com/app/merchant/all/10/1&#8243;
};

$http(request).success(function(response){
$scope.items=response.data;
}).error(function(errorMessage) {
console.log(errorMessage);
})

}];

build one page app by using bootstrap working with angular.js from begginng–to be continue

If you are an front end developer working with a team, the back code developer already build the api arrow you to access the data and give your the specify header required and then you could quickly build a page by using bootstrap to make the layout looking mobile friendly and angular.js can access api server very easy.

If there is not backend code involved then using subline could achieve that.

Could see below links:

http://sandywebdesigner.com/csb

here is the looking on desktop
angular01

looking in mobile:

angular02

Time for home, will continue tomarrow, write the code how to build using angular.js and bootstrap to quickly build an app for retrieve customize header request.

Using bower to add client side recource into your specify folder–Build a node.js website–part4

Now it is time to add clents size recource file into your specify folders, in my project I create a public folder to hold all the css and js,

In node.js there are a plug called bower will install the client packages for you.

1) In the root director create a file named .bowerrc and put an object inside the file:{“directory” : “public/lib”} this is to tell bower where you like to put your client sie resource

2) before to run bower, need change the .bowerrc file encoding , go to file advace save options,choose Western European(windows)-Codepage 1252

nodejsWebsite11

3) run bower install <packages name your want to install>

Tip:

1)make sure you have bower installed, if not run npm install bower -g (g meaning globle level)

2)the bower need git working with it, make sure your git install at globle level.

3)what I mean globle level, just need have path in your system, if you didn’t install git in globle level, you could manually add you path to it. if you don’t know how to add path just simply uninstall git and reinstall it , when install it this time make sure you select it install in globle level.

gitInstall

 

Since bootstrap is commonly used in a lot website and I am also very confident withe working with bootstrap. now it’s time using bower to install bootstrap

nodejsWebsite12

After that then just put the css and js file into the layout.vash

nodejsWebsite13

 

 

Create marquee news in front page and the news is read from the database with expired data,also included management page to insert news

My boss just saw other company website has a marquee new on the front page, so she asked me if I could make one and arrow her to insert news and the news will dispear at the expired data.

For achieve that task, first I create a table in my database table, here is my table:

breadNewTable

then I write a store proceedure, a little tip for fresh guy, alway use store preceedure to insert data for security reasons.

breadNewStoreProceedure

Now, We could start the front end job. I create a user control:marquee.ascx(so you could put it in anyway you like), to display the new, here is my html code:

frontUCmarquee

here is the backcod, I used ado.net to open the database and qurery what I need, and bind it to my BulledtedList:

databasereadertomarquee

See the code this if(!IsPostBack) is not neccessary, but I use web froms so it wil inherit maintain state so I don’t need retrieve database everytime postback.

here I am also happy to share the css file for style this unorder list to display inline:

MarqueeCssStyle

A tip for fresh guy, put this in the page your use control will stand it.

Now, you just need drag the usercontrol to any page you want it with this css style in top of the header it. You coud see it.

Then We could start create a page to arrow my boss to insert the bread news, I used boostrap format so it save my time to write css. here is the front page look like:

addNews

here is the html code:

htmlCodeAddnews

The form use jQury Validate, the jquery-ui.js, is for my boss click then will pop up the jQuery calender to arrow her to put the expired date. So simple isn’t, I am love JQure very much, save a lot of time. It remind me when I first time write javascript over 10 years ago, for every simply function I need write a lot codes.

Finally I just need write a event could be fired by this button.

storeIntodatabase

Ok, That’s all. Have fun!

Using c# code to force bootstrap modal stay open after page postback

Recently I write a small function into my asp.net application.To enable the driver to input the time the submit the pick up client and drop off the client time.
My boss like the pick up time and drop off time should been populate by just click.so I write a code on the back of page to retrive the time every time the driver click the button.
But the dropoff button driver me to nuts,Because When the dropoff button click I pop out the bootstrap modal.But the problems came out this button need make page postback to retrive the current time and after postback my modal need stay open.
It take me a while to fix out this.
Here is my solution.
first, I need write javascript like this is for to open the modal: #dropoffModal is my hidden modal.

 function openModal() {
$('#dropoffModal').modal({ show: true });
}
 

Second I have the the button is like this(See the button click will fire a event named:”Button_DropOff_Click” behind it):

 button_click_event_fire_javascript

Finally, just write your event on the page behind file:


protected void Button_DropOff_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}

here just a solution. by the way, You could use ScriptManager.RegisterStartupScript() this command call another function in your frond page javascript.

Bootrap Jumbotron into WordPress Theme

In this post I will use a bootstrap Jumbotron template,here is the link http://getbootstrap.com/examples/jumbotron/  I will  customize it into wordpress theme

You need download bootstrap into” yourtheme “folder, whatever theme name you like to call it.

bootstrap_to_wordpress2

 

Those fold should inside your theme folder, don’t worry what are inside it except everything from bootstrap, the other file is empty now.

1) for wordpress could read you theme you need put those on top of your style.css:

/*
Theme Name: Bootstrap to WordPress
Theme URI: http://sandywebdesigner.com
Author: Sandy Zhang
Author URI: http://sandywebdesigner.com
Description: Example theme for  how to convert static Bootstrap site into dynamic WordPress theme
Version: 1.0
License:
License URI:
Text Domain: bootstrap-to-wp

This theme, like WordPress, is licensed under the GPL.
Use it to make something cool, have fun, and share what you’ve learned with others.
*/

/* Move down content because we have a fixed navbar that is 50px tall */
body {
padding-top: 50px;
padding-bottom: 20px;
}
.admin-bar .navbar-fixed-top {
margin-top: 30px;
}
/* Below is the style for navigation in functions.php add a class to sub-menu to the navigation so I just write a simple style to it,you could customize it by yourself */
@media (min-width:768px) {
.sub-menu {
display: none;
position: absolute;
background: #222;
padding: 10px 15px;
width: 150px;
}

li:hover .sub-menu {
display: block;
}

}

.sub-menu li {
margin-bottom: 10px;
list-style: none;
}

.sub-menu li:last-child {
margin-bottom: 0;
}

.sub-menu a  {
color: #999;
text-decoration: none;
}

.sub-menu a:hover  {
color: #fff;
}

.current-menu-item > a, .current-menu-parent > a {
background: #000;
}
.current-menu-parent li a {
background: inherit;
}
.current-menu-parent .current-menu-item a {
color: #fff;
font-weight: bold;
}

.sidebar{
margin-top:40px;
color:#444;
}
.sidebar h3{
color:#888;
}
.widget{
margin:10px 0 30px;
}
article .post{
margin:20px 0;
}

.featured-image img,
.portfolio-piece img,
.portfolio-image img {
max-width:100%;
}

.prev-next{
font-size:24px;
margin-top:30px;
text-align:right;
}

@media (max-width:540px) {
.portfolio-piece h4{
font-size:.8em;
}
.prev-next{
font-size:15px;
margin-top:15px;
text-align:right;
}

}

2)header.php

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset=”<?php bloginfo( ‘charset’ ); ?>”>
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<link rel=”shortcut icon” href=”<?php bloginfo(‘template_directory’);?>/images/favicon.ico”>

<title>
<?php wp_title(‘|’,true,’right’);?>
<?php bloginfo(‘name’)?>

</title>

<?php wp_head(); ?>
</head>

<body <?php body_class(); ?>>

<div class=”navbar navbar-inverse navbar-fixed-top” role=”navigation”>
<div class=”container”>
<div class=”navbar-header”>
<button type=”button” class=”navbar-toggle” data-toggle=”collapse” data-target=”.navbar-collapse”>
<span class=”sr-only”>Toggle navigation</span>
<span class=”icon-bar”></span>
<span class=”icon-bar”></span>
<span class=”icon-bar”></span>
</button>
<a class=”navbar-brand” href=”<?php bloginfo(‘url’); ?>”><?php bloginfo(‘name’); ?></a>
</div>
<div class=”navbar-collapse collapse”>
<?php
$args = array(
‘menu’ => ‘mainmenu’,
‘menu_class’ => ‘nav navbar-nav’,
‘container’ => ‘false’
);
wp_nav_menu($args);
?>
</div><!–/.navbar-collapse –>
</div>
</div>

3)footer.php

<hr>

<footer>
<p>&copy; <?php bloginfo(‘name’);?> <?php echo date(‘Y’); ?></p>
</footer>
</div> <!– /container –>
<?php wp_footer(); ?>
</body>
</html>

3)index.php

<?php get_header(); ?>

<div class=”container”>

<div class=”row”>
<div class=”col-md-9″>
<?php if(have_posts()):while(have_posts()):the_post();?>
<div class=”Page-header”>
<h1><?php the_title(); ?></h1>
</div>
<?php the_content();?>
<?php endwhile; else:?>

<div class=”Page-header”>
<h1>Oh no!</h1>
</div>
<p>No content is appearing for this page!</p>
<?php the_content();?>

<?php endif;?>

</div>
<?php get_sidebar(); ?>

</div>

<?php get_footer(); ?>

4)functions.php

<?php
function theme_styles(){
wp_enqueue_style( ‘bootstrap_css’, get_template_directory_uri() . ‘/css/bootstrap.min.css’ );
wp_enqueue_style( ‘main_css’, get_template_directory_uri() . ‘/style.css’ );
}
add_action( ‘wp_enqueue_scripts’, ‘theme_styles’ );

function theme_js(){
global $wp_scripts;
wp_register_script( ‘html5_shiv’, ‘https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js&#8217;, ”, ”, false );

wp_register_script( ‘respond_js’, ‘https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js&#8217;, ”, ”, false );

$wp_scripts->add_data( ‘html5_shiv’, ‘conditional’, ‘lt IE 9’ );
$wp_scripts->add_data( ‘respond_js’, ‘conditional’, ‘lt IE 9’ );
wp_enqueue_script( ‘bootstrap_js’, get_template_directory_uri() . ‘/js/bootstrap.min.js’, array(‘jquery’), ”, true );
wp_enqueue_script( ‘theme_js’, get_template_directory_uri() . ‘/js/theme.js’, array(‘jquery’,’bootstrap_js’), ”, true );

}

add_action( ‘wp_enqueue_scripts’, ‘theme_js’ );

add_theme_support(‘menus’);
add_theme_support(‘post-thumbnails’);

function register_theme_menus() {
register_nav_menus(
array(
‘header-menu’    => __( ‘mainmenu’ )
)
);
}
add_action( ‘init’, ‘register_theme_menus’ );

function create_widget( $name, $id, $description ) {

register_sidebar(array(
‘name’ => __( $name ),
‘id’ => $id,
‘description’ => __( $description ),
‘before_widget’ => ‘<div class=”widget”>’,
‘after_widget’ => ‘</div>’,
‘before_title’ => ‘<h2>’,
‘after_title’ => ‘</h2>’
));
}

create_widget( ‘Front Page Left’, ‘front-left’, ‘Displays on the left of the homepage’ );
create_widget( ‘Front Page Center’, ‘front-center’, ‘Displays in the center of the homepage’ );
create_widget( ‘Front Page Right’, ‘front-right’, ‘Displays on the right of the homepage’ );
?>

See how simple it is, index.php you completed, then use this index.php to create other template like page.php. single.php, etc. Have fun!