Building MVC 4 App with Bootstrap layout

Prerequisites: VS2013, MVC 4

First let’s create a default MVC4 application using VS.

Go to menu File –> New Project –> Installed –> Templates –> Visual C# –> Web –> Select “ASP.NET MVC 4 Web Application” –> name application as “MVC_Bootstrap”

Now just run the application and see if everything is working. Sounds good….

Now right click the MVC_Bootstrap web project –> Manage Nuget Package –> Online –> in top right search text area enter “bootstrap” and click search. (look for package created by: Twitter, Inc)

The above step, would add bunch of bootstrap css files in Content folder and  bunch of JS files in Scripts folder. Plz verify… Sounds good.

Open the _layout.cshtml file and below tags in HEAD section or you can add proper bundle configuration in App_Start/BundleConfig.cs file


<link href="@Url.Content("~/Content/bootstrap.min.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/bootstrap-theme.min.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/bootstrap.min.js")"></script>

Things to know about Bootstrap :

css class “container-fluid”:  This is usually applied to main DIV of the body. This div should hold entire HTML for proper layout.

css class “row”: All rows should be applied with this class, this applies width in percentage. If you want to go with PX go with row-fluid.

Entire screen width is divided into 12 equal columns ( 1 to 12)

For our application we will have header and the followed by content

1) First let’s fix _Layout.cshtml page, so open this page and remove all html (HEADER, BODY & FOOTER) content inside the body tag

2) Let’s add 3 div’s as shown below. So here what we are doing is we are creating a container div and adding 3 div’s

a) header,

b) body and

c) footer

3) Each row is embedded with a column of width


<body>
 <div class="container-fluid">
<div class="row">
 <div class="col-sm-12 col-md-12 col-lg-12">
 <h6> HEADER </h6>
 </div>

</div>
 <div class="row">
 <div class="col-sm-12 col-md-12 col-lg-12">
 @RenderBody()
 </div>
 </div>
 <div class="row">
 <div class="col-sm-12 col-md-12 col-lg-12">
 <h6> FOOTER </h6>
 </div>
 @Scripts.Render("~/bundles/jquery")
 @RenderSection("scripts", required: false)
</div>
 </div>
 @Scripts.Render("~/bundles/jquery")
 @RenderSection("scripts", required: false)
</body>

Now lets add below action in HOME controller

public ActionResult MyForm()
{
            return View();
}

Add MyForm.cshtml in folder Views ==> Home

add below content to MyForm CSHTML. In this we have divided column into sum of 12 .

<div class="container-fluid">
 <div id="MyForm" class="row">
 <div class="col-sm-12 col-md-12 col-lg-12">
 <div class="row">
 <div class="col-sm-1 col-md-1 col-lg-1">
 <div class="labelClass">Name:</div>
 </div>
 <div class="col-sm-2 col-md-2 col-lg-2">
 <select id="User" name="User" style="width: 100%">
 <option>Select</option>
 <option>User1</option>
 </select>
 </div>
 <div class="col-sm-1 col-md-1 col-lg-1">
 <div class="labelClass">Lead Name:</div>
 </div>
 <div class="col-sm-2 col-md-2 col-lg-2">
 <input id="LeadName" name="LeadName" type="text" value="" style="width: 100%">
 </div>
 <div class="col-sm-1 col-md-1 col-lg-1">
 <div class="labelClass">Date:</div>
 </div>
 <div class="col-sm-2 col-md-2 col-lg-2"><input type="date" style="width: 100%" /> </div>
 <div class="col-sm-1 col-md-1 col-lg-1">
 <div class="labelClass">Country:</div>
 </div>
 <div class="col-sm-2 col-md-2 col-lg-2">
 <select id="Country" name="Country" style="width: 100%">
 <option>Select</option>
 <option>Select 1</option>
 </select>
 </div>
 </div>
 </div>
 </div>
</div>
 

Now when you run this application this all controls would be aligned properly.

Now try to resize the window to as small as you can and you would notice that the controls would auto align themselves one below another. You can also change your screen resolution and verify the same.

Happy Kooding… Hope this was helpful…..!

Advertisement

Removing a Row from KENDO GRID

In this article, will demonstrate how to remove multiple grid items when a button is clicked.

Below is basic grid configuration.



@(Html.Kendo().Grid<User>()
           .Name("UserGrid")
            .HtmlAttributes(new { style = "height:100%; width:100%; " })
            .Columns(columns =>
            {
                       columns.Bound(m => m.Id).Hidden(true);
                       columns.Bound(m => m.Name).Width(175).Title("Name");
                       columns.Bound(m => m.Hours).Width(175).Title("Hrs");
                       columns.Bound(m => m.Comments).Width(175).Title("Comments");
            }
            )
            .Scrollable()
            .ToolBar(toolbar => toolbar.Template(@<text>
                       <a class="k-button k-button-icontext k-grid-add" href="#"><span class="k-icon k-add"></span>New</a>
                       <a class="k-button k-button-icontext" id="cancelItem" 
href="javascript:void(0)"><span class="k-icon k-cancel"> </span>Cancel</a>

           </text>))
            .Editable(editable => editable.Mode(GridEditMode.InCell))
            .Filterable()
            .Sortable()
            .DataSource(dataSource => dataSource
            .Ajax()
            .Batch(true)
            .ServerOperation(false)
            .Model(model =>
                       {
                       model.Id(row => row.Id);
                       }
                       )
            .ServerOperation(false)
            .PageSize(25)
            )
            .Resizable(resize => resize.Columns(true))
            .Selectable(selectable => selectable.Mode(GridSelectionMode.Multiple))
            .Reorderable(reorder => reorder.Columns(true))
            .Pageable(p => p.PageSizes(new[] { 25, 50, 100 }))
 )



Below are the key configurations. We defining that our grid is multi selectable. Also we defined Cancel button in Grid toolbar


.Selectable(selectable => selectable.Mode(GridSelectionMode.Multiple))

<a class="k-button k-button-icontext" id="cancelItem" href="javascript:void(0)"><span class="k-icon k-cancel"></span>Cancel</a>

Now its time to define the Javascript, which will remove the grid item. Find the INLINE comments for the below code.


// adding click event for cancel button

$("#cancelItem").on("click", function (e) { 
           clearSelectedRows("UserGrid"); 
 });

clearSelectedRows = function (gridName) {

           // identifying grid

            var entityGrid = $("#" + gridName + "").data("kendoGrid");

            // finding all the selected rows
            var rows = entityGrid.select();
            rows.each(function (index, row) {

                        // reading each selected item
                         var selectedItem = entityGrid.dataItem(row);

                       // finally removing selected item from grid data source
                         entityGrid.dataSource.remove(selectedItem); 
              });
 }

Happy Kooding… Hope this helps….!

Upload & Read Excel File

This article demonstrate

1) How to upload the file in MVC

2) Read excel file content

How to upload the file in MVC

In your MVC razor view add the below html content

@using(Html.BeginForm("Upload", "Home", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
    <table>
        <tr>
            <td>File:</td>
            <td>
                <input type="file" name="UploadedFile" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" name="Submit" value="Submit" />
            </td>
        </tr>
    </table>
}

Notice, the action name : Upload, Controller Name: Home

Now come to home controller and add action called Upload

 public ActionResult Upload(FormCollection formCollection)
        {
            if (Request != null)
            {
                HttpPostedFileBase file = Request.Files["UploadedFile"];

                if ((file != null) && (file.ContentLength &gt; 0) && !string.IsNullOrEmpty(file.FileName))
                {
                    string fileName = file.FileName;
                    string fileContentType = file.ContentType;
                    byte[] fileBytes = new byte[file.ContentLength];
                    var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));

		}
	    }
	}

Now try to run the app by putting a breakpoint and see if all is working until now

Now add dll called EPPLUS from NUGET which is used for reading and writing files.

Lets say I have file with FirstName & LastName

Now add a class called users

public class Users
{
      public string FirstName { get; set; }

       public string LastName { get; set; }
}

Now lets modify our action method to read the file stream object which we uploaded. Add using OfficeOpenXml; statement


 public ActionResult Upload(FormCollection formCollection)
        {
            if (Request != null)
            {
                HttpPostedFileBase file = Request.Files["UploadedFile"];

                if ((file != null) && (file.ContentLength &gt; 0) && !string.IsNullOrEmpty(file.FileName))
                {
                    string fileName = file.FileName;
                    string fileContentType = file.ContentType;
                    byte[] fileBytes = new byte[file.ContentLength];
                    var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));

                    var usersList = new List&lt;Users&gt;();

                    using (var package = new ExcelPackage(file.InputStream))
                    {
                        var currentSheet = package.Workbook.Worksheets;
                        var workSheet = currentSheet.First();
                        var noOfCol = workSheet.Dimension.End.Column;
                        var noOfRow = workSheet.Dimension.End.Row;

                        for (int rowIterator = 2; rowIterator &lt;= noOfRow; rowIterator++)
                        {
                            var user = new Users();
                            user.FirstName = workSheet.Cells[rowIterator, 1].Value.ToString();
                            user.LastName = workSheet.Cells[rowIterator, 2].Value.ToString();
                            usersList.Add(user);
                        }


                    }
                }
            }

            return View("Index");
        }

Finally all the users will be available in usersList object.

Happy Kooding…. Hope this helps!!

Error: multiple actions were found that match the request

If this error is happening with Web API then below is the reason

Usually App_Start/WebApiConfig contains route as


config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });

So change the above configuration to


config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });

Happing Kooding… !

How to use Kendo Validator / Kendo Validation

For example, I have form which has Salary as input field, now I would like to perform custom validation on this field.

HTML


<div id="DataEntryDiv" style="margin-top:20px">
<div class="editor-label">Salary</div>
<div class="editor-field">
<input id="Salary" type="number" class="input" name="Salary" data-bind="value: Salary" />
</div>
</div>

JAVASCRIPT


<script type="text/javascript">
var myValidator = $("#DataEntryDiv").kendoValidator({

rules: {
SalaryRule: function (input) {
if (input.is("[name=Salary]")) {
return !(parseInt($("#Salary").val()) <= 0);
}
return true;
}
},
messages: {
SalaryRule: "Value must be greater than 0",
},
validateOnBlur: false
}).data("kendoValidator");

function onSave(e) {
if (!myValidator.validate()) {
e.preventDefault();
}
}
</script>

This works with Kendo Grid Pop as well. All you have to do is hook up the save event for kend Grid


@(Html.Kendo().Grid<MyModelClass>()
.Name("myKendoGrid")

.Events(e => e.Save("onSave"))

Happy Kooding… Hope this helps!

Parse Date string using Kendo in Javascript

If your date is in /Date(“14201020200”)/ format and would like to format this date string to MM/dd/yyyy using Kendo??

If yes then the syntax to do that is


kendo.toString(kendo.parseDate(dateString), 'MM/dd/yyyy')

Happy Kooding… Hope this helps!