Search code examples
jqueryjquery-bootgrid

How to display image in jquery-bootgrid


I am using jquery-bootgrid for display list of records.

These records have image also but images are not display in rows.

Anybody knows how to display images in rows?


Solution

  • You will have to use formatters. Below is an example. Here, data is loaded from the database via ajax:

    <table id="gridStudents" class="table table-condensed table-hover table-striped">
            <thead>
                <tr>
                    <th data-column-id="StudentId" data-type="numeric" data-identifier="true">Student Id</th>
                    <th data-column-id="FirstName">First Name</th>
                    <th data-column-id="LastName">Last Name</th>
                    <th data-column-id="Photo" data-formatter="pix">Photo</th>
                </tr>
            </thead>
    </table>
    

    Then, in your javascript, do the following (assuming you have a controller named Student and 2 actions named getStudents and getPhoto(int StudentId), which respectively fetch all the students and get the photograph of a specific student based on his or her StudentId) :

    $(function () {  
        var jqxhr = $.ajax({
             url: 'Student/getStudents',
             type: 'POST'
        });
        jqxhr.done(function (data, textStatus, jqXHR) {
            $("#gridStudents").bootgrid({
                caseSensitive: false,
                selection: true,
                multiSelect: true,
                formatters: {                    
                    "pix": function (column, row) {
                        return "<img src=\"Student/getPhoto/" + row.StudentId + "\" />";
                        }
                    }
            }).bootgrid("append", data)
        });
    });
    

    Below is what the server side would look like. Here the photos are stored as binary data in a field named Photo in the database, and another field named ContentType stores the content type (image/jpeg, image/png, etc.):

    [Authorize]
    public class StudentController : Controller
    { 
        .... //your other stuff....
    
        [HttpPost]
        public JsonResult getStudents()
        {
            var data = db.Students.ToList();
            return Json(data, JsonRequestBehavior.AllowGet);
        }
    
        public ActionResult getPhoto(int StudentId)
        {
            var student = db.Students.Find(StudentId);
            return File(student.Photo, student.PhotoContentType);
        }
    
    }