ASP. NET MVC uses the bootstrap system (2)--using bootstrap CSS and HTML elements

Source: Internet
Author: User
Tags button type

Read Catalogue

    • Bootstrap Grid (GRID) system
    • Bootstrap HTML Elements
    • Bootstrap validation Style
    • ASP. NET MVC creation contains bootstrap style edit template
    • Summary

Bootstrap provides a rich set of CSS settings, HTML elements, and advanced raster systems to help developers quickly lay out web pages. All CSS styling and HTML elements combined with mobile-first streaming raster systems allow developers to quickly and easily build intuitive interfaces without worrying about the specifics of responding on smaller devices.

Back to top bootstrap grid (GRID) system

In mobile internet today, more and more websites are accessed by mobile devices, and mobile traffic has soared in recent years. Bootstrap provides a responsive, mobile-first streaming raster system that is automatically divided into up to 12 columns as the screen or viewport (viewport) size increases.

Grid parameters

Bootstrap 3 provides a series of predefined classes to specify the size of the column, as follows:

The Bootstrap grid system is divided into 12 columns, and when you layout your Web page, remember that the sum of all the columns should be 12. For illustration, see the following HTML:

<div class= "Container" >    <div class= "Row" >        <div class= "col-md-3" style= ">            

Note: Bootstrap needs to wrap a. Container container for the page content and grid system.

In the above code, I added a div container with class container and a child div element row. The row div element has 3 columns in turn. 2 of these columns contain the class of col-md-3, a column containing the Col-md-6 class. When they are grouped together, they add up to a sum of 12. But this HTML code is only for devices that are used for display resolution >=992. So in order to better respond to low-resolution devices, we need to combine different CSS raster class. To add support for tablets, phones, and low-resolution PCs, you need to include the following class:

<div class= "Container" >    <div class= "Row" >        <div class= "col-xs-3 col-sm-3 col-md-3" style= "" >            
Back to top bootstrap HTML element

Bootstrap has prepared a whole bunch of HTML elements with styles, such as:

    • Tables
    • Buttons
    • Forms
    • Images
Bootstrap Tables (form)

Bootstrap provides the default styles for HTML tables and the option to customize their layout and behavior. For a better presentation, I use the classic Northwind sample database and the following techniques:

    • Using ASP. NET MVC as a Web application application
    • Bootstrap front-end frame
    • Entity Framework as an ORM framework
    • StructureMap performs dependency injection and control inversion of our project, using NuGet to install
    • AutoMapper automatically maps the domain model to the view model, using NuGet to install

Open Visual Studio, create an ASP. NET MVC project, by default, VS has added a bootstrap file for us. To see the effect, follow these steps to implement:

    • Add a Productviewmodel under the models file in the ASP. NET MVC Project
   public class Productviewmodel    {public        int ProductId {get; set;}        public string ProductName {get; set;}        Public decimal? UnitPrice {get; set;}        public int? UnitsInStock {get; set;}        public bool discontinued {get; set;}        public string Status {get; set;}    }
    • Add the Automapperconfig class to the App_Data folder and, through AutoMapper, create a conditional mapping for the Productviewmodel status property, if product is discontinued, Then the status is danger, if UnitPrice is greater than 50, the Status property is info, and if Unitinstock is less than 20, then the status is set to warning. The logic of the code is as follows:
    Mapper.createmap<product, productviewmodel> ()                . Formember (dest = dest. Status,                    opt + = opt. Mapfrom                        (src = src. Discontinued                            ? "Danger"                            : src. UnitPrice >                                ? "Info"                                : src. UnitsInStock < 20? "Warning": "));
    • Add a Productcontroller and create an action named index
public class Productcontroller:controller    {        ////        GET:/product/        Private readonly Applicationdbcontext _context;        Public Productcontroller (Applicationdbcontext context)        {            This._context = context;        }        Public ActionResult Index ()        {            var products = _context. Products.project (). To<productviewmodel> (). ToArray ();            return View (products);        }    }
    1. The code above uses dependency injection to get the entity Framework DbContext object, and the Index action accepts the return products collection from the database and then uses AutoMapper to map to each Productviewmodel object. Finally, the data is returned for the view.
    2. Use bootstrap HTML table on a view to display data
View Code

The rendered data is as follows:

Bootstrap Tables remaining styles

Bootstrap provides an extra style to decorate the table. For example, using table-bordered to display the border,table-striped shows the odd even row color (zebra stripe),table-hover , as the name implies, when the mouse move line highlighting, by adding. The table-condensed class can make the table more compact and the inner complement (padding) in the cell is halved, and the modified code looks like this:

<table class= "Table table-bordered table-striped table-hover" ></table>

The results shown are as follows:

Bootstrap context Table Style

Bootstrap provides an additional class that allows us to modify the styles of <td> and <tr>, providing the following class:

    • Active
    • Success
    • Info
    • Warning
    • Danger

Modify the above code to add styles to <tr> dynamically:

<tr class= "@item. Status > <td>            @Html. displayfor (ModelItem = Item. ProductName)        </td>        <td>            @Html. displayfor (ModelItem = Item. UnitPrice)        </td>        <td>            @Html. displayfor (ModelItem = Item. UnitsInStock)        </td>        <td>            @Html. displayfor (ModelItem = Item. Discontinued)        </td>    </tr>}

The effect after the update is as follows:

Bootstrap Buttons

Bootstrap offers many different colors and sizes of buttons, providing 6 colors and 4 sizes for the core buttons, as well as displaying different styles by setting the class property:

? BTN Btn-primary Btn-xs

? BTN Btn-default BTN-SM

? BTN Btn-default

? BTN btn-sucess BTN-LG

You can set the color class for the button:

? Btn-default

? Btn-primary

? Btn-success

? Btn-info

? Btn-warning

? Btn-danger

So you can use the following code to render the effect:

<div class= "Row" >    <!--default button--    <button type= "button" class= "btn btn-default btn-xs" >        Default & Size=mini    </button>    <button type= "button" class= "btn btn-default btn-sm" >        Default & size=small    </button>    <button type= "button" class= "Btn Btn-default" >default </button>    <button type= "button" class= "btn btn-default btn-lg" >        default & Size=large    </button></div>

The display results are as follows:

Bootstrap form (form)

Forms are common in most business applications, so a unified style helps to improve the user experience, and Bootstrap provides a number of different CSS styles to beautify the form.

    • Level form

Html.BeginForm with ASP. NET MVC makes it easy to create a form that creates a bootstrap horizontal display form by adding a class named Form-horizontal to <form>.

View Code

In the code above, 2 Html methods (Html.labelfor, html.textboxfor) are wrapped using the <div> element of Class Form-group, which allows the bootstrap validation style to be applied to the form element. Of course you can also use the bootstrap raster col-* class to specify the width of the elements in the form, as shown below:

    • Vertical form

Bootstrap basic forms are displayed vertically by default, and after you remove the class for form-horizontal and Class col-* in the Html.BeginForm Help method, the following effects are displayed:

    • Inline form

An inline form means that all form elements are arranged one after the other , only for the viewport (viewport) at least 768px in width (the viewport width is smaller, which causes the form to collapse).

remember to add a label label, and if you do not set a label label for each input control, the screen reader will not recognize it correctly. For these inline forms, you can hide them by setting the. Sr-only class for the label . the detailed code is as follows:

View Code

The display results are as follows:

Bootstrap Image

In Bootstrap 3.0, you can make a picture support a responsive layout by adding a. Img-responsive class to the picture. Its essence is to set the max-width:100% for the picture, Height:auto; and Display:block; property, which allows the picture to be scaled better in its parent element.

You can make a picture appear in a different shape by adding the following appropriate class for the element.

    • img-rounded
    • Img-circle
    • Img-thumbnail

Take a look at the following code:

<div class= "Row" >    

Back to top bootstrap validation style

By default, the ASP. NET MVC project template supports unobtrusive validation and automatically adds the required JavaScript libraries to the project. However, the default validation does not use the CSS specified by bootstrap. When an INPUT element fails validation, the JQuery validation plugin adds a Input-validation-error class (in the presence of site.css) to the element. How about not modifying the jquery validation plugin and using the bootstrap built-in error style?

Bootstrap provides the class as a style in Has-error (the label font changes to red, the input element with a red border) to display an error:

<div class= "Form-group has-error" >    @Html labelfor (m = m.username, new {@class = "col-md-2 Control-label"} )    <div class= "col-md-10" >        @Html. textboxfor (M = m.username, new {@class = "Form-control"})    </ Div></div>

So, I need to dynamically bind/remove Has-error for <div class= ' from-group ' > elements. In order not to modify the Jquery.validation plugin, I add the Jquery.validate.bootstrap file in the Scripts folder:

$.validator.setdefaults ({    highlight:function (Element) {        $ (element). Closest ('. Form-group '). AddClass (' Has-error ');    },    unhighlight:function (Element) {        $ (element). Closest ('. Form-group '). Removeclass (' Has-error ');    },});

This script modifies the default jquery validation plug-in settings by calling the SetDefaults method. See I use the highlight and Unhighlight methods to dynamically Add/Remove Has-error class.

Finally, add it to the package file

Bundles. ADD (New Scriptbundle ("~/bundles/jqueryval"). Include ("~/scripts/jquery.validate.js", "~/scripts/jquery.validate.unobtrusive.js", "~/scripts/ Jquery.validate.bootstrap.js "));

Note: By default, ASP. NET MVC uses a wildcard * to package the jquery.validate* file into a jqueryval file, as follows:

Bundles. ADD (New Scriptbundle ("~/bundles/jqueryval"). Include (

"~/scripts/jquery.validate*"));

But jquery.validate.bootstrap.js must be loaded after the jquery validate plugin, so we can only explicitly specify the file order to package because by default the order in which the loaded files are packaged is in alphabetical order represented by wildcards.

Back to top ASP. NET MVC create template with bootstrap style edit
    • Primitive type

Editor template refers to the automatic generation of form input elements in an ASP. NET MVC application where the data type based on the property of the object is rendered through the razor view. ASP. NET MVC contains a number of editing templates, and of course we can implement extensions. The edit template is similar to the detail view, but the local view is rendered by name, and the edit template is rendered by type.

Give me a chestnut, @Html. editorfor (model = model. property), if the property type is string, then @html.editor creates a type=text INPUT element, and if the property type is password, a type= is created The input element of the password. So the Editorfor helper renders the generated HTML based on the data type of the model attribute.

But the drawback is that the default generated HTML is as follows:

You can see class= "Text-box single-line", but as mentioned earlier, the Bootstrap form element class must be Form-control.

So, in order for editor helper to generate a form element with class Form-control, we need to create a custom edit template to rewrite the old template. You need to do the following:

    • Create a folder in the shared folder named EditorTemplates ( note the same name )
    • Add the file named string.cshtml ( note the same name ) and add the following code:
@model String@html.textbox ("", ViewData.TemplateInfo.FormattedModelValue, new{    @class = "Form-control"})

In the above code, we call the @Html. TextBox method, and pass an empty string as the textbox's name. This will cause the model's property name to be the name of the generated textbox, and the textbox displays the value of model, appended with the attribute named class, and its value is "Form-control".

Rebuild the project and discover the newly generated INPUT element whose class has been changed to "Form-control". As shown below:

    • Non-primitive type

ASP. NET MVC allows developers to create editing templates based on custom DataType , such as automatically generating multi-line text boxes and stipulating rows of 3 rows, and the same thing:

    • Add Multilinetext. Cshtml (Note the same name) file into EditorTemplates
    • Add the following code:
@model String@html.textarea ("", ViewData.TemplateInfo.FormattedModelValue.ToString (), new {@class = "Form-control", rows = 3})
    • To make the properties of our model take the multilinetext.cshtml edit template at render time, we need to specify DataType attribute as Multilinetext for the property:
[DataType (Datatype.multilinetext)]  

The final display looks like this:

Back to the top of the summary

This article introduces Bootstrap's responsive layout (grid) and briefly describes the HTML elements in bootstrap, including table, Button, Form, Image .... It then modifies the default settings of the jquery validate plugin to make it friendly to support the error style in bootstrap. Finally, I explored the edit template in ASP. NET MVC, so that the generated INPUT element automatically contains the Form-control style.

ASP. NET MVC uses the bootstrap system (2)--using bootstrap CSS and HTML elements

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.