How to bind uploadBox in ejGrid
To upload an image through Grid editing mode, it is recommended to use the template editing modes of the Grid. Such as Dialog Template, InlineForm Template, External Form Template. Along, with this ejUploadBox would be rendered in the form to upload and preview the image.
Render the Grid control with the respective editing template and ActionComplete (to render different controls in the form).
<div id="Grid"></div> <script type="text/javascript"> $(function () { $("#Grid").ejGrid({ dataSource: new ej.DataManager({ json: window.gridData, insertUrl: "NormalUpdate", removeUrl: "NormalDelete", updateUrl: "NormalUpdate" }), allowPaging: true, dataBound: "actionComplete", toolbarSettings: { showToolbar: true, toolbarItems: ["add", "edit", "delete", "update", "cancel"] }, editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, editMode: "inlineformtemplate", inlineFormTemplateID: "#template" }, columns: [ { field: "OrderID", headerText: "Order ID", textAlign: ej.TextAlign.Right }, { field: "EmployeeID", headerText: "Employee ID", editType: "dropdownedit", dataSource: window.employeeView, textAlign: ej.TextAlign.Right }, { field: "Freight", format: "{0:C}", textAlign: ej.TextAlign.Right }, { field: "CustomerID", headerText: "Customer ID" }, { field: "ShipCity", headerText: "Ship City" } ] }); }); </script>
Razor:
@using Syncfusion.JavaScript.Models @(Html.EJ().Grid<OrdersView>("Grid") .AllowPaging() .Datasource(ds => { ds.Json((IEnumerable<object>)ViewBag.datasource); ds.UpdateURL("NormalUpdate"); ds.InsertURL("NormalInsert"); ds.RemoveURL("NormalDelete"); ds.Adaptor(AdaptorType.RemoteSaveAdaptor); }) .EditSettings(edit => { edit.AllowAdding() .AllowDeleting() .AllowEditing() .EditMode(EditMode.InlineFormTemplate) .InlineFormTemplateID("#template"); }) .ToolbarSettings(toolbar => { toolbar.ShowToolbar().ToolbarItems(items => { items.AddTool(ToolBarItems.Add); items.AddTool(ToolBarItems.Edit); items.AddTool(ToolBarItems.Delete); items.AddTool(ToolBarItems.Update); items.AddTool(ToolBarItems.Cancel); }); }) .Columns(col => { col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true) .TextAlign(TextAlign.Right).Add(); col.Field("EmployeeID").HeaderText("EmployeeID") .DataSource(ViewBag.data) .TextAlign(TextAlign.Right).Add(); col.Field("Freight").HeaderText("Freight") .TextAlign(TextAlign.Right) .Format("{0:C}").Add(); col.Field("CustomerID").HeaderText("Customer ID").Add(); col.Field("ShipCity").HeaderText("Ship City").Add(); }) .ClientSideEvents(events=>events.ActionComplete("actionComplete")) )
public class HomeController : Controller { public ActionResult Index() { ViewBag.datasource = OrderRepository.GetAllRecords().ToList(); ViewBag.data = new NorthwindDataContext().EmployeeViews.ToList(); return View(); } public ActionResult NormalUpdate(EditableOrder value) { OrderRepository.Update(value); var data = OrderRepository.GetAllRecords(); return Json(value, JsonRequestBehavior.AllowGet); } public ActionResult NormalInsert(EditableOrder value) { OrderRepository.Add(value); var data = OrderRepository.GetAllRecords(); return Json(value, JsonRequestBehavior.AllowGet); } public ActionResult NormalDelete(int key) { OrderRepository.Delete(key); var data = OrderRepository.GetAllRecords(); return Json(data, JsonRequestBehavior.AllowGet); } }
Webforms:
<ej:DataManager ID="DataMgr" runat="server" UpdateURL="Default.aspx/UrlUpdate" InsertURL="Default.aspx/UrlInsert" RemoveURL="Default.aspx/UrlDelete" Adaptor="remoteSaveAdaptor" /> <ej:Grid ID="Grid" runat="server" DataManagerID="DataMgr" AllowPaging="true"> <EditSettings AllowEditing="True" AllowAdding="True" AllowDeleting="True" InlineFormTemplateID="#template" EditMode="InlineFormTemplate"></EditSettings> <ToolbarSettings ShowToolbar="true" ToolbarItems="add,edit,delete,update,cancel"></ToolbarSettings> <Columns> <ej:Column Field="OrderID" IsPrimaryKey="true" TextAlign ="Right" HeaderText="Order ID" /> <ej:Column Field="EmployeeID" HeaderText="Employee ID" TextAlign ="Right" /> <ej:Column Field="Freight" HeaderText="Freight" /> <ej:Column Field="CustomerID" HeaderText="Customer ID" /> <ej:Column Field="ShipCity" HeaderText="ShipCity" /> </Columns> <ClientSideEvents ActionComplete="actionComplete" /> </ej:Grid>
namespace sqlbinding { public partial class _Default : Page { public static List<Orders> order = new List<Orders>(); List<object> drpObj = new List<object>(); protected void Page_Load(object sender, EventArgs e) { this.DataMgr.Json = order; this.Grid.Columns[1].DataSource = drpObj; } [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static void UrlUpdate(Orders value) { Orders result = order.Where(o => o.OrderID == value.OrderID).FirstOrDefault(); if (result != null) { result.OrderID = value.OrderID; result.OrderDate = value.OrderDate; result.CustomerID = value.CustomerID; result.EmployeeID = value.EmployeeID; result.Freight = value.Freight; result.ShipCity = value.ShipCity; } } [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static object UrlInsert(Orders value) { order.Insert(0, value); return order; } [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static object UrlDelete(int key) { Orders result = order.Where(o => o.OrderID == key).FirstOrDefault(); order.Remove(result); return order; } } }
Define the actionComplete event and template element. Render the ejUploadBox in the event and bind them fileSelect event to preview the image as well as save them for uploading to the server-end.
Once the Grid saved the records to the sever end, an external ajax post has been submitted to upload the saved image.
<script> window.uploadData = {};//A Global var to track and hold file uploading info function uploadFile(args, proxy) { args.data["Photo"] = window.uploadData.files; window.uploadData["editData"] = new FormData(); //Converting the grid data to form data to send files to controller for (var d in args.data) uploadData.editData.append(d, args.data[d]); //Updating the form before sending the ajax post $.ajax({ url: "/UploadFile.ashx", contentType: false, processData: false, type: 'POST', data: uploadData.editData, success: function () { proxy.element.ejWaitingPopup("hide"); } }); } function actionComplete(args) { if (args.requestType == "save") { this.element.ejWaitingPopup("show"); uploadFile(args,this); } if (args.requestType == "beginedit" || args.requestType == "add") { $("#Freight").ejNumericTextbox({ value: parseFloat($("#Freight").val()), width: "116px", height: "28px", decimalPlaces: 2 }); $("#EmployeeID").ejDropDownList({ width: '116px', value: args.rowData.EmployeeID, fields: {text: "EmployeeID", value: "EmployeeID" }, dataSource: this.model.columns[1].dataSource }); $("#UploadInput").ejUploadbox({ buttonText: { browse: "Select Photo" }, fileSelect: function (args) { //Get the file from fileSelect event uploadData["files"] = args.files[0].rawFile; //inially copying the file to global variable and same can be retrieved in the save action. var filename = args.files[0].name; } }); if (args.requestType == "beginedit") { $("#OrderID").attr("disabled", "disabled"); $("#ShipCountry").ejDropDownList("setSelectedValue", args.row.children().eq(1).text()); } } } </script>
<script type="text/template" id="template"> <b>Order Details</b> <table cellspacing="10"> <tr> <td style="text-align: right;"> Order ID </td> <td style="text-align: left"> <input id="OrderID" name="OrderID" value="{{: OrderID}}" disabled="disabled" class="e-field e-ejinputtext valid e-disable" style="text-align: right; width: 116px; height: 28px" /> </td> <td style="text-align: right;"> Customer ID </td> <td style="text-align: left"> <input id="CustomerID" name="CustomerID" value="{{: CustomerID}}" class="e-field e-ejinputtext valid" style="width: 116px; height: 28px" /> </td> </tr> <tr> <td style="text-align: right;"> Freight </td> <td style="text-align: left"> <input type="text" id="Freight" name="Freight" value="{{:Freight}}" /> </td> <td style="text-align: right;"> Employee ID </td> <td style="text-align: left"> <input id="EmployeeID" name="EmployeeID"> </td> </tr> <tr> <td style="text-align: right;"> Ship City </td> <td style="text-align: left"> <input id="ShipCity" name="ShipCity" value="{{: ShipCity}}" class="e-field e-ejinputtext valid" style="width: 116px; height: 28px" /> </td> </tr> <tr> <td style="text-align: right;"> <div class="posupload">Select a file to upload </div> </td> <td style="text-align: left"> <div id="UploadInput"></div> </td> </tr> </table> </script>
A Generic handler UploadFile.ashx.cs, has been used to save the image to the server folder. Refer to the following code example.
public class UploadFile : IHttpHandler { public void ProcessRequest(HttpContext context) { var file = context.Request.Files[0]; string targetFolder = HttpContext.Current.Server.MapPath("uploadfiles"); //creating a folder for saving a file if (!Directory.Exists(targetFolder)) { Directory.CreateDirectory(targetFolder); } if (file != null && file.ContentLength > 0) { string fileName = Path.GetFileName(file.FileName); fileName = HttpContext.Current.Request.Form.GetValues("OrderID")[0] + "." + fileName.Split('.')[1]; file.SaveAs(Path.Combine(targetFolder, fileName)); } context.Response.Write("Success"); } }
Figure 1 Grid with Previewed image and uploadbox.