$(document).ready(function () { if ($('#frmClientsSearch').length === 1) { $("input[name=searchClientName]").focus(); $("input[name=searchClientName]").select(); } var scope = $('#sform'); $('input[type=submit]', scope).click(function (e) { try { e.preventDefault(); if (!scope.valid()) { alert('has invalid'); return; } save(scope); } catch (e) { alert("Error " + e); } }); $("input[name=searchClientName]").keyup(function (event) { if (event.keyCode === 13) { $("#btnClientsSearch").click(); } }); }); // http://www.ienablemuch.com/2011/11/flexigrid-crudinline-form-with-aspnet.html var formHtml = ""; function canRender() { return _canRender; } $(function () { _canRender = false; }); $("#flexClients").flexigrid({ url: '/Client/Client/', dataType: 'json', colModel: [ { display: 'Client Id', name: 'Id', width: 100, sortable: true, align: 'center', hide: true }, { display: 'Client #', name: 'Number', width: 100, sortable: true, align: 'center' }, { display: 'Name', name: 'Name', width: 350, sortable: true, align: 'center' }, { display: 'Contact 1', name: 'Contact1', width: 350, sortable: true, align: 'center' }, ], buttons: [ { name: 'Add', bclass: 'add', onpress: add }, { name: 'Edit', bclass: 'edit', onpress: edit }, { name: 'Delete', bclass: 'delete', onpress: del }, { separator: true } ], searchitems: [ { display: 'Client Name', name: 'Name' } ], sortname: "Name", sortorder: "asc", usepager: true, title: 'Clients', useRp: true, rp: 15, rpOptions: [5, 10, 15, 20, 25, 40], showTableToggleBtn: true, width: 900, onSuccess: bindDblClick, onSubmit: addFormData, hideOnSubmit: false, height: 'auto', singleSelect: true }); //$('.flexigrid').on('dblclick', 'tr[id*="row"]', function () { // // console.log('mouseenter rowId: ' + $(this).attr('id').substr(3)); // alert($(this).attr('id').substr(3)); // //Edit(); //}); function bindDblClick() { $('#flexClients tr').dblclick(function () { var id = $(this).attr('id'); id != '' || (id = $('#flexClients tr').index(this)); edit('Edit'); }); } //This function adds parameters to the post of flexigrid. You can add a verification as well by return to false if you don't want flexigrid to submit function addFormData() { //passing a form object to serializeArray will get the valid data from all the objects, but, if the you pass a non-form object, you have to specify the input elements that the data will come from var dt = $('#sform').serializeArray(); dt = dt.concat($('#frmClientsSearch').serializeArray()); $("#flexClients").flexOptions({ params: dt }); return true; }; $('#sform').submit(function () { $('#flexClients').flexOptions({ newp: 1 }).flexReload(); return false; }); function del(com, grid) { try { var clientName = $('.trSelected td:eq(2)').text(); if (clientName) //Variable is defined and not empty { if (confirm("Are you sure you want to delete " + $.trim(clientName) + "?")===false) return false; $('.trSelected', grid).each(function () { var id = $(this).attr('id'); id = id.substring(id.lastIndexOf('row') + 3); addFormData(); $('#flexClients').flexOptions({ url: '/Client/Delete/'+ id }).flexReload(); }); } } catch(e) { alert('Error ' + e); } } function add(com, grid){ $("#sform").dialog({ autoOpen: false, show: "blind", width: 1000, height: 600 }); $("#sform").dialog("open"); clearForm(); $('#fntype').val('Add'); } function edit(com, grid) { $('.trSelected', grid).each(function () { var id = $(this).attr('id'); id = id.substring(id.lastIndexOf('row') + 3); var url = '/Client/Edit/' + id; $("#sform").load(url).dialog({ modal: true, width: 1000, height: 600 }); //$("#sform").dialog({ // autoOpen: false, // show: "blind", // width: 1000, // height: 600 //}); //$("#sform").dialog("open"); //clearForm(); //$('#fntype').val('Edit'); //$('#Id').val($('.trSelected td:eq(0)').text()); //$('#Number').val($('.trSelected td:eq(1)').text()); //$('#Name').val($('.trSelected td:eq(2)').text()); //$('#Contact1').val($('.trSelected td:eq(3)').text()); }); } function clearForm() { $("#sform input").val(""); } $(function () { $('#btnSave').click(function () { addFormData(); $('#flexClients').flexOptions({ url: '/Client/Client/' }).flexReload(); clearForm(); $('#sform').dialog('close'); return false; }); }); $(function () { $('#btnCancel').click(function () { //clearForm(); $('#sform').dialog('close'); return; }); }); $(function () { $('#btnClientsSearch').click(function () { addFormData(); $('#flexClients').flexOptions({ url: '/Client/Client/' }).flexReload(); }); });This is the Client.cshtml
@model CardNumbers.Objects.Client @{ ViewBag.Title = "Clients"; } @section scripts { <script src="@Url.Content("~/Scripts/Clients.js")" type="text/javascript" ></script> } <form id="frmClientsSearch"> <label for="clientNo">Client No: </label> <input type="number" name="searchClientNo" class="numericOnly" /><br /> <label for="clientName">Client Name: </label> <input type="text" size="25" value="Please enter the search value" class="SelectOnEntry" name="searchClientName" /> <input type="button" id="btnClientsSearch" value="Find / Refresh" /> </form> <div style="padding-left: 150px; padding-top: 50px; padding-bottom: 50px;" id="ClientsResults"> <table id="flexClients" style="display: none"> </table> </div> <div id="editor" style="visibility: hidden"> @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "sform", title = "Client Info" })) { Html.Partial("_ClientForm", Model); } </div>This is ClientController.cs
using System; using System.Linq; using System.Web.Mvc; using CardNumbers.Models; using CardNumbers.Data; namespace CardNumbers.Controllers { public class ClientController : Controller { private IClientRepository Db; public ClientController() { this.Db = new ClientRepository(new CardNumbersContext()); } public ClientController(IClientRepository Db) { this.Db = Db; } #region Search public ActionResult Search(int? searchClientNo = null, string searchClientName = null) { // Assume we want to select everything var clients = Db.Clients; // Should set type of clients to IQueryable<Clients> if ((searchClientNo ?? 0) != 0) //Number was supplied clients = clients.Where(c => (c.Number == searchClientNo)); // If clientNo was supplied, clients is now filtered by that. If not, it still has the full list. The following will further filter it. if (!String.IsNullOrWhiteSpace(searchClientName)) // Part of the name was supplied clients = clients.Where(c => (c.Name.Contains(searchClientName))); return PartialView("_ClientsSearch", clients); // return PartialView("_Client", clients); } #endregion #region Client [HttpGet] public ActionResult Client(int id = 0) { return View(); } /// <summary> /// This method is invoked from the flexigrid /// </summary> /// <param name="formValues"></param> /// <param name="searchClientNo"></param> /// <param name="searchClientName"></param> /// <returns></returns> [HttpPost] public ActionResult Client(FormCollection formValues) { // Assume we want to select everything var clients = Db.Clients; // Should set type of clients to IQueryable<Clients> int searchClientNo = 0; int.TryParse(formValues["searchClientNo"], out searchClientNo ); string searchClientName = formValues["searchClientName"].ToString(); if (searchClientNo == 0 && searchClientName == "Please enter the search value") clients = clients.Where(c => (c.Number == searchClientNo)); else { if (searchClientNo != 0) //Number was supplied clients = clients.Where(c => (c.Number == searchClientNo)); // If clientNo was supplied, clients is now filtered by that. If not, it still has the full list. The following will further filter it. if (!String.IsNullOrWhiteSpace(searchClientName)) // Part of the name was supplied clients = clients.Where(c => (c.Name.Contains(searchClientName))); } int page = int.Parse(formValues["page"] ?? "1"); int rp = int.Parse(formValues["rp"]); string qtype = formValues["qtype"].ToString(); string query = (formValues["query"] ?? "").ToString(); string sortname = (formValues["sortname"] ?? "Name").ToString(); string sortorder = (formValues["sortorder"] ?? "asc").ToString(); if (!string.IsNullOrEmpty(sortname) && !string.IsNullOrEmpty(sortorder)) { clients = clients.OrderBy(sortname, (sortorder == "asc")); } if (!string.IsNullOrEmpty(qtype) && !string.IsNullOrEmpty(query)) { clients = clients.Like(qtype, query); } int Total = clients.Count(); clients = clients.Skip((page - 1) * rp).Take(rp); var flexgrid = new { page = page, total = Total, rows = clients .Select(x => new { id = x.Id, cell = new { Id = x.Id, Number = x.Number, Name = x.Name, Contact1 = x.Contact1.Contact ?? String.Empty } } ) }; return Json(flexgrid, JsonRequestBehavior.AllowGet); } #endregion Client public ActionResult QuickSearch(string term) { var clients = from c in Db.Clients where c.Name.Contains(term) orderby c.Name select new { label = c.Name }; return Json(clients, JsonRequestBehavior.AllowGet); } public ActionResult Index() { return View(); } // // GET: /Client/Details/5 public ActionResult Details(int id) { return View(); } // // GET: /Client/Create public ActionResult Create() { return View(); } // // POST: /Client/Create [HttpPost] public ActionResult Create(FormCollection collection) { try { // TODO: Add insert logic here return RedirectToAction("Index"); } catch { return View(); } } // GET: /Client/Edit/5 public ActionResult Edit(int id) { var client = Db.GetClientById(id); return PartialView("_ClientForm",client); } // // POST: /Client/Edit/5 [HttpPost] public ActionResult Edit(int id, FormCollection collection) { try { // TODO: Add update logic here return RedirectToAction("Index"); } catch { return View(); } } // // GET: /Client/Delete/5 public ActionResult Delete(int id) { return View(); } // // POST: /Client/Delete/5 [HttpPost] public ActionResult Delete(int id, FormCollection collection) { try { Db.DeleteClient(id); return this.Client(collection); } catch { return View(); } } } }