1. NuGet

Install the BForms.MVC package via NuGet Manager in your MVC project. This process will include the BForms JS Framework in your Scripts folder and will add references to the BForms and RequireJsNet assemblies. The JavaScript and CSS components come in two forms, as individual files and as minified bundles.

Scripts/
    └── BForms/
        ├── Bundles/
        │   ├── css/
        │   ├── fonts/
        │   ├── images/
        │   └── js/
        ├── Components/
        ├── Plugins/
        ├── Stylesheets/
        └── Widgets/
            

2. Validation provider

BForms comes with its custom validation provider. In order to set it up, add the following line in the Application_Start() method (found in Global.asax):

Register the BForms validation provider

public class MvcApplication : System.Web.HttpApplication
{
	protected void Application_Start()
	{
		AreaRegistration.RegisterAllAreas();

		FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
		RouteConfig.RegisterRoutes(RouteTable.Routes);
		BundleConfig.RegisterBundles(BundleTable.Bundles);

		//register BForms validation provider
		ModelValidatorProviders.Providers.Add(new BsModelValidatorProvider());
	}
}
            

3. Include CSS

The next step is to add the BForms CSS file to your bundles. Go to the RegisterBundles method in App_Start\BundleConfig.cs and add the following code:

Register the CSS bundle

public static void RegisterBundles(BundleCollection bundles)
{

    bundles.Add(new StyleBundle("~/BForms")
        //BForms CSS bundle
        .Include("~/Scripts/BForms/Bundles/css/*.css", new CssRewriteUrlTransform())
        );
}
            

Ok! You have added a new bundle, but you also have to use it. Go to Layout.cshtml (or any other layout you are using) and modify the head tag like the one below:

Include the CSS bundle in your layout

<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" 
        content="initial-scale=1, 
        width=device-width, 
        maximum-scale=1, 
        user-scalable=no">

    @Styles.Render("~/BForms")

    @*For IE7-8 support of HTML5 elements and responsive*@
    <!--[if lt IE 9]>
    <script src="@Url.Content("~/Scripts/BForms/Bundles/js/iefix.js")" 
    type="text/javascript">
    </script>
  <![endif]-->
</head>

            

4. Include JS

The next step is to include the BForms javascript components in your project. There are two ways of working with BForms JS components: using RequireJS.NET (recommended) or by referencing the javascript files directly from the ~/Scripts/Bforms/Bundles/js folder.

You can read more here: AMD, RequireJS and RequireJS.NET

Using RequireJS

RequireJS comes in handy when you want a release version of your app. Inside the ~/Scripts/Bforms folder there are 2 configuration files for javascript files: RequireJS.json and RequireJS.Release.json. To use them both include the following code in your layout:

@using BForms.Html
@using RequireJS

<!DOCTYPE html>
<html>
  ...
  <body>
    ...

    @if (HttpContext.Current.IsDebuggingEnabled)
        {
            @Html.RenderRequireJsSetup(
				new RequireRendererConfiguration
                    {
                        BaseUrl = Url.Content("~/Scripts"),
                        RequireJsUrl = 
				Url.Content("~/Scripts/bforms/components/requirejs/require.js"),
                        ConfigurationFiles = new []
                                                {
                                                    "~/Scripts/BForms/RequireJS.json"
                                                }
                    })
        }
        else
        {
            @Html.RenderRequireJsSetup(
				new RequireRendererConfiguration
                    {
                        BaseUrl = Url.Content("~/Scripts"),
                        RequireJsUrl = 
				Url.Content("~/Scripts/bforms/components/requirejs/require.js"),
                        ConfigurationFiles = new[]
                                                {
                                                    "~/Scripts/BForms/RequireJS.Release.json"
                                                }
                    })
            @Html.Partial("_Tracking")
        }

  </body>
</html>
            

Without RequireJS - Include JS with ASP.NET bundling

You need to include a bundle for javascript files too (as you did before with the css files). Copy the following code in your RegisterBundles:

public static void RegisterBundles(BundleCollection bundles)
{
	bundles.Add(new ScriptBundle("~/BFormsJS").IncludeDirectory(
		"~/Scripts/BForms/Bundles/js","*.js"));
}
            

5. RequireJS configuration

First of all, you need to remember that this step is optional. You only need to do it if you want additional configuration options for your RequireJS installation.

Let's say you want to add a script to your project. Create RequireJS.json and RequireJS.Release.json as in the image bellow:

Configuration files

Note that selected files from the above image are new. The BForms package comes with its own configuration, which you can find under Scripts/BForms.

Now that we have our files, let's add references to our scripts. To show you how to do this we have created a script called main-script.js under Scripts/Controllers/Common, which contains only a console.log statement.

Main-script file


console.log("Message from main-script.js. Script was loaded because you have referenced it from your custom RequireJS.json/RequireJS.Release.json")
            

Add the path in your newly created configuration files. For example, RequierJS.config should look like this:

Configuration files content

{
  "path": {
    "main-script": "controllers//common//main-script"
  }
}
            

As you can see in the code above we have added the path to our scripts (just one in our case) without the .js extension. We don't need to prefix our path with Scripts/ because RequireJS will automatically search there.

Don't forget to update your _Layout.cshtml

@using BForms.Html
@using RequireJS

<!DOCTYPE html>
<html>
  ...
  <body>
    ...

    @if (HttpContext.Current.IsDebuggingEnabled)
        {
            @Html.RenderRequireJsSetup(
			new RequireRendererConfiguration
                        {
                            BaseUrl = Url.Content("~/Scripts"),
                            RequireJsUrl = 
				Url.Content("~/Scripts/bforms/components/requirejs/require.js"),
                            ConfigurationFiles = new []
                                                    {
                                                        "~/Scripts/BForms/RequireJS.json",
																			// added for extra configuration
                                                        "~/RequireJS.json" 
                                                    }
                        })
        }
        else
        {
            @Html.RenderRequireJsSetup(
			new RequireRendererConfiguration
                        {
                            BaseUrl = Url.Content("~/Scripts"),
                            RequireJsUrl = 
				Url.Content("~/Scripts/bforms/components/requirejs/require.js"),
                            ConfigurationFiles = 
				new[]
					{
						"~/Scripts/BForms/RequireJS.Release.json",
						// added for extra configuration
						"~/RequireJS.Release.json" 
					}
                        })
            @Html.Partial("_Tracking")
        }

  </body>
</html>
            

Internationalization

In order to setup the resources, you first need to add the following line in the Application_Start() method (Global.asax):

BForms.Utilities.BsResourceManager.Register(Resources.Resource.ResourceManager);
            

Keys

After setting that up, you should now define the keys in your resource files.

Grid


BF_GroupEditorMoveToGroups Default Value : "Move to groups"
BF_Items Default value: "items"
BF_New Default value : "New"
BF_NoResults Default value: "There are no results"
BF_Of Default value: "of"
BF_Reset Default value : "Reset"
BF_ResultsPerPage Default value: "results per page"
BF_Save Default value : "Save"
BF_Search Default value : "Search"
BF_Select Default value : "Select"

Example

Thumbs up! Now that everything is set up you can start working on your new project. Let's say you want to add a dropdown element somewhere in your application. Read the following steps and you'll see how easy it is.

Model definition - step 1

You need to create your model. Let's name it Demo.
As we said earlier, we need to add a dropdown property.

[Display(Name = "My demo bforms dropdown", Prompt = "Select an option")]
[BsControl(BsControlType.DropDownList)]
public BsSelectList<int?> DemoDropdown { get; set; }
            

If you haven't read the BForms documentation yet, the BsControl annotation helps you define what kind of control you want to render for that property. You can find a list of values for the BsControlType enum here.

The Display annotation comes with ASP.NET and, in our case, we used the properties Name (the output of the Html.BsLabelFor helper) and Prompt (a placeholder value shown in your dropdown before you select anything).

Another important aspect is the type argument of the generic class BsSelectList<>. Upon form submission, the type of the SelectedValues property for your DemoDropdown will be int? since DemoDropdown was declared as BsSelectList<int?>. Had we defined it as BsSelectList<string>, DemoDropdown.SelectedValues would be of type string.

Data binding - step 2

We have a dropdown but we need to fill it with some data. You can do this from a database, but we will show you how it can be done from an enum.

public enum DemoEnum : int
{
    Option1 = 1,
    Option2 = 2,
    Option3 = 3,
    Option4 = 4
}

            

We recommend that you use our helper:

demoModel.DemoDropdown = BsSelectList<int?>.FromEnum(typeof(DemoEnum));
            

There's also another way if you want to write more code:

demoModel.DemoDropdown = new BsSelectList<int?>
{
	Items = Enum.GetValues(typeof(DemoEnum)).Cast<DemoEnum>()
		.Select(x => new BsSelectListItem
		{
			Text = x.ToString(),
			Value = ((int)x).ToString()
		}).ToList();
};
            

Controller - step 3

We showed you earlier how to bind data and now you will see where to use it.

public ActionResult Index()
{
    var demoModel = new Demo()
    {
		DemoDropdown = BsSelectList<int?>.FromEnum(typeof (DemoEnum))
    };

    return View(demoModel);
}

            

View - step 4

@using (Html.BsBeginForm())
{
	<div class="col-lg-12 form-group ">
		<div class="input-group">
			@Html.BsSelectFor(s => s.DemoDropdown)
		</div>
	</div>	
}
            

Writing the view is very simple. We have a form which has a class named js-demoForm (remember this because it is important) and an Html helper @Html.BsSelectFor (similar to @Html.DropDownListFor) that renders a dropdown.

Don't forget to add @model Demo to your view.

Javascript - step 5

First of all you need to create a folder named Controllers under Scripts. After that, if you're not working in an area, create a folder called Root under Controllers (that you have created few seconds ago). Otherwise, replace Root with the area name.

Create a new folder that has the same name as your controller inside the folder you've just created.
Finally you just have to add a javascript file which has to be named like this:.

controller_name-action_name.js (eg: home-index.js)

In the end you should have something like this:

Scripts/
    └── Controllers/
        ├── Common/
        │   └── main-script.js
        │
        ├── Root/
        │   └── Home/
        │	└──home-index.js
        │
        └── area_name/
            

Javascript code from home-index.js:

require([
         'bforms-initUI',
], function () {
    var HomeIndex = function (options) {
        this.options = $.extend(true, {}, options);
    };

    HomeIndex.prototype.init = function () {
        this.$demoForm = $(".js-demoForm");

        //apply BForms plugins
        this.$demoForm.bsInitUI(this.options.styleInputs);
    };

    $(document).ready(function () {
        var ctrl = new HomeIndex(requireConfig.pageOptions);
        ctrl.init();
    });
});
            

The important part is in HomeIndex.prototype.init function. As you can see, we have selected our form (.js-demoForm, remember ?) and we have applied bforms on it. That's all you have to do.

This is how your home page should look like: