Tuesday, 29 November 2016

Pagination in Mvc Grid

View

@(Html.Awe().Grid("CustomQueryingGrid")
.Url(Url.Action("GetItems", "CustomQueryingGrid"))
.Height(450)
.Columns(
new Column { Bind = "Id", Groupable = false, Sortable = false, Width = 70 },
new Column { Bind = "Person" },
new Column { Bind = "Food" }))

Controller

public class CustomQueryingGridController : Controller
{
public ActionResult GetItems(GridParams g)
{ const int PageSize = 10;
var items = Db.Lunches.AsQueryable();
if (g.SortNames != null)
{
IOrderedQueryable orderedItems = null;
// doing this for demo purposes
// one might use something like Dynamic Linq
// or generate a sql string etc.
for (int i = 0; i < g.SortNames.Length; i++)
{
var column = g.SortNames[i];
var direction = g.SortDirections[i];
if (i == 0)
{
if (column == "Person")
orderedItems = direction == "asc"
? items.OrderBy(o => o.Person)
: items.OrderByDescending(o => o.Person);
else if (column == "Food")
orderedItems = direction == "asc"
? items.OrderBy(o => o.Food)
: items.OrderByDescending(o => o.Food);
}
else
{
if (column == "Person")
orderedItems = direction == "asc"
? orderedItems.ThenBy(o => o.Person)
: orderedItems.ThenByDescending(o => o.Person);
else if (column == "Food")
orderedItems = direction == "asc"
? orderedItems.ThenBy(o => o.Food)
: orderedItems.ThenByDescending(o => o.Food);
}
}
items = orderedItems;
}
var count = items.Count();
var totalPages = (int)Math.Ceiling((float)count / PageSize);
var page = items.Skip((g.Page - 1) * PageSize).Take(PageSize);
return Json(new GridModelBuilder(page.AsQueryable(), g)
{
Key = "Id",
Map = o => new { o.Id, o.Person, o.Food },
PageCount = totalPages,
ItemsCount = count
}.Build());
}
}

File Upload In Mvc

In web development projects, file uploading is a very common feature. The question always arises of how to upload a file or how to create these kinds of features in MVC applications. This article explains how the FileUpload control works with MVC, how to upload a file, how to open an uploaded file and how to delete an uploaded file.

In simple HTML we define the FileUpload control like this:

<input type="file" name="file_Uploader" />



This HTML control has a TextBox and a button. When you click on the button a file open dialog box will open automatically. You choose a file and your file path will apear in the text box, these features are built into the FileUpload control.

See the following code.

First we will create a model FileModel.cs with the following code.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace MvcApplication1.Models

{

    public class FileUploadModel

    {

        public string FileName { get; set; }

        public string FilePath { get; set; }

    }

}


In the code above we have the FileUploadModel class, in this class we have the following two auto implemented properties:

1. FileName
2. FilePath.

  1. Now add a new Controller FileUploadController.cs with the following code:

    publicActionResult FileUpload()
    {
       
    return View();
    }

  2. Now add a new view FileUpload.cshtml wih the following code:

@model MvcApplication1.Models.FileUploadModel

<script src="~/Scripts/jquery-1.9.1.min.js"></script>

<script type="text/javascript">

    $(document).ready(function () {

 

        if('@ViewBag.Message' == 'File Uploaded Successfully')

        {

            alert('File Uploaded Successfully');

        }

 

        if ('@ViewBag.Message' == 'File is already exists') {

            alert('File is already exists');

        }

 

        $('#uloadTable td img.link').live('click', function () {

            var filename = $(this).parent().parent().parent().attr('id');

            $(this).parent().parent().parent().remove();

 

            $.ajax({

                type: "post",

                url: "/FileUpload/RemoveUploadFile?fileName=" + filename,

                datatype: "json",

                traditional: true,

                success: function (data) {

 

                    alert('File Deleted');

                    if (data == 0) {

                        $('#uloadTable').remove();

                    }

                   

                }

            });

        });

    });

 

</script>

 

@{

    ViewBag.Title = "FileUpload";

}

 

<h2>File Upload</h2>

 

@using (@Html.BeginForm("FileUpload", "FileUpload", FormMethod.Post, new { @id = "form1", @enctype = "multipart/form-data" }))

{

           

    <table>

        <tr>

            <td>

                <input type="file" name="file_Uploader" />

            </td>

            <td>

               

                <input type="submit" id="bttn_Upload" value="Upload" />

            </td>

        </tr>

 

    </table>

    if (Session["fileUploader"] != null)

    {

    <div class="upload">

        <div style="width: 500px;">

            <table id="uloadTable" border="1">

                <thead>

                    <tr>

                        <th>Name</th>

                        <th>Action</th>

                    </tr>

                </thead>

 

                <tbody>

                    @foreach (var item in (List<MvcApplication1.Models.FileUploadModel>)Session["fileUploader"])

                    {

                        <tr id="@item.FileName">

                            <td>@item.FileName</td>

                            <td style="text-align: center"><a class="viewc"  href="@Url.Action("OpenFile", "FileUpload", new { @fileName = item.FileName })">

                                <img width="16" height="16" border="0" src="~/Images/view.png" class="viewc"></a>

                                <a class="viewc" href="">

                                    <img width="16" height="16" border="0" src="~/Images/Delete.png" class="link"></a></td>

                        </tr>

                    }

 

                </tbody>

            </table>

 

        </div>

    </div>

    }

}


Here the important thing is that we need to remember always, when we work with the file upload control always add this with form tag @enctype = "multipart/form-data"
as in the following:

@using (@Html.BeginForm("FileUpload", "FileUpload", FormMethod.Post, new { @id = "form1", @enctype = "multipart/form-data" }))

Now create a new folder in your application, in this application I create MyFiles. And now add the following code in to "FileUploadController.cs".
 

using MvcApplication1.Models;

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace FileUploader.Controllers

{

    public class FileUploadController : Controller

    {

        //

        // GET: /FileUpload/

 

        public ActionResult FileUpload()

        {

            return View();

        }

 

        [HttpPost]

        public ActionResult FileUpload(HttpPostedFileBase file_Uploader)

        {

            if (file_Uploader!=null)

            {

                string fileName = string.Empty;

                string destinationPath = string.Empty;

 

                List<FileUploadModel> uploadFileModel = new List<FileUploadModel>();

 

                fileName = Path.GetFileName(file_Uploader.FileName);

                destinationPath = Path.Combine(Server.MapPath("~/MyFiles/"), fileName);

                file_Uploader.SaveAs(destinationPath);

                if (Session["fileUploader"] != null)

                {

                    var isFileNameRepete = ((List<FileUploadModel>)Session["fileUploader"]).Find(x => x.FileName == fileName);

                    if (isFileNameRepete == null)

                    {

                        uploadFileModel.Add(new FileUploadModel { FileName = fileName, FilePath = destinationPath });

                        ((List<FileUploadModel>)Session["fileUploader"]).Add(new FileUploadModel { FileName = fileName, FilePath = destinationPath });

                        ViewBag.Message = "File Uploaded Successfully";

                    }

                    else

                    {

                        ViewBag.Message = "File is already exists";

                    }

                }

                else

                {

                    uploadFileModel.Add(new FileUploadModel { FileName = fileName, FilePath = destinationPath });

                    Session["fileUploader"] = uploadFileModel;

                    ViewBag.Message = "File Uploaded Successfully";

                }

            }

            return View();

        }

 

        [HttpPost]

        public ActionResult RemoveUploadFile(string fileName)

        {

            int sessionFileCount = 0;

 

            try

            {

                if (Session["fileUploader"] != null)

                {

                    ((List<FileUploadModel>)Session["fileUploader"]).RemoveAll(x => x.FileName == fileName);

                    sessionFileCount = ((List<FileUploadModel>)Session["fileUploader"]).Count;

                    if (fileName != null || fileName != string.Empty)

                    {

                        FileInfo file = new FileInfo(Server.MapPath("~/MyFiles/" + fileName));

                        if (file.Exists)

                        {

                            file.Delete();

                        }

                    }

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

 

            return Json(sessionFileCount, JsonRequestBehavior.AllowGet);

        }

 

 

        public FileResult OpenFile(string fileName)

        {

            try

            {

                return File(new FileStream(Server.MapPath("~/MyFiles/" + fileName), FileMode.Open), "application/octetstream", fileName);

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }

 

 

 

    }

}

Understand the code
 

[HttpPost]

public ActionResult FileUpload(HttpPostedFileBase file_Uploader)

{


Here we have the parameter HttpPostedFileBase, the question now arises of what it is.

HttpPostedFileBase is an abstract class that has the following properties that are helpful to determine everything about your selected file, that you chose from the file upload control

  1. Contentlength: Lenth of file

  2. Contenttype: Type of file

  3. FileName: Name of file

  4. InputStream: For reading the contents of file

This is also helpful for a "saveas" of your file into your server folder destination where you want to save it.

One thing to always remember is that when you declare a HttpPostedFileBase, the variable name should be the same as you gave as the name of your HTML control name as in the following example:
 

public ActionResult FileUpload(HttpPostedFileBase file_Uploader)

 

<input type="file" name="file_Uploader" />

Both names are the same, "file_Uploader".



After uploading files:



If you upload a file with the same name then you will get an alert message saying it is not possible to load a file with the same name into the folder.

How to delete a file

[HttpPost]

        public ActionResult RemoveUploadFile(string fileName)

        {

            int sessionFileCount = 0;

 

            try

            {

                if (Session["fileUploader"] != null)

                {

                    ((List<FileUploadModel>)Session["fileUploader"]).RemoveAll(x => x.FileName == fileName);

                    sessionFileCount = ((List<FileUploadModel>)Session["fileUploader"]).Count;

                    if (fileName != null || fileName != string.Empty)

                    {

                        FileInfo file = new FileInfo(Server.MapPath("~/MyFiles/" + fileName));

                        if (file.Exists)

                        {

                            file.Delete();

                        }

                    }

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

 

            return Json(sessionFileCount, JsonRequestBehavior.AllowGet);

        }

$('#uloadTable td img.link').live('click', function () {

            var filename = $(this).parent().parent().parent().attr('id');

            $(this).parent().parent().parent().remove();

 

            $.ajax({

                type: "post",

                url: "/FileUpload/RemoveUploadFile?fileName=" + filename,

                datatype: "json",

                traditional: true,

                success: function (data) {

 

                    alert('File Deleted');

                    if (data == 0) {

                        $('#uloadTable').remove();

                      

                    }

                   

                }

            });

        });

In the code above, we are sending the filename on a RemoveUploadFile action method.

url: "/FileUpload/RemoveUploadFile?fileName=" + filename,

This code will send the file name into your action parameter. If it finds the file name it will delete the file, from that folder.
 

if (fileName != null || fileName != string.Empty)

                    {

                        FileInfo file = new FileInfo(Server.MapPath("~/MyFiles/" + fileName));

                        if (file.Exists)

                        {

                            file.Delete();

                        }

                    }


So that's it. For any query please send your comments, I will definitely help you out. Happy Programming.