We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

how to open file upload dialog to upload file on cell click in batch edit mode.

Hello,

I am using grid with batch edit mode. everything works but i am having the following problems related to batch mode-

1. When i select a date from date picker  and move to another cell , i can't see the date which i selected in previous cell but when i save the data ,the date is getting passed to controller. Once the page is refreshed then it becomes visible , but during edit mode its not visible.  see the below image 



2. How to upload file when clicked on the grid cell in batch mode to server and display the file name on the cell,which can further be stored in database as file path.
i tried using jquery fileupload clsss but it needs id to open a file directory.

this is how i initialize the grid  -


                    @(Html.EJ().Grid<object>("FlatGrid")
                    .Datasource(ds => ds.URL(Url.Action("SpDetailDataSource", "CRUD", null, Request.Url.Scheme)).BatchURL(Url.Action("SpDetailBatchUpdate", "CRUD", null, Request.Url.Scheme)).Adaptor(AdaptorType.UrlAdaptor))

                    .EnableAltRow()
                    .AllowFiltering()
                    .SelectedRowIndex(0)
                    .IsResponsive()
                    .AllowSorting()
                    .GridLines(GridLines.Horizontal)
                    .EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing().EditMode(EditMode.Batch); })
                    .PageSettings(page =>
                    {
                        page.PageSize(5);
                    })
                    .AllowTextWrap()
                    .AllowResizeToFit()
                    .EnableHeaderHover()
                    .FilterSettings(filter => { filter.FilterType(FilterType.Excel); })
                    .AllowPaging()
                    .ClientSideEvents(eve =>
                    {
                        eve.ActionComplete("complete");
                        eve.ActionFailure("failure");
                        eve.ActionBegin("beginAction");
                        eve.CellEdit("onCellEdit");

                    })
                    .Columns(col =>
                    {
                        col.Field("documentId").HeaderText("Department ID").IsPrimaryKey(true).Visible(false).TextAlign(TextAlign.Left).ValidationRules(v => v.AddRule("required", true).AddRule("number", true)).Width(70).Add();
                        col.Field("documentCode").HeaderText("Doc. Code").TextAlign(TextAlign.Left).Add();

                        col.Field("description").HeaderText("Description").TextAlign(TextAlign.Left).Width(70).Add();
                        col.Field("documentNumber").HeaderText("Doc. Number").TextAlign(TextAlign.Left).Width(65).Add();
                        col.Field("issueDate").HeaderText("Issue Date").TextAlign(TextAlign.Left).Width(45).EditType(EditingType.Datepicker).Add();

                        col.Field("expiryDate").HeaderText("Expiry Date").TextAlign(TextAlign.Left).Width(45).EditType(EditingType.Datepicker).Add();
                        col.Field("remarks").HeaderText("Remarks").TextAlign(TextAlign.Left).Width(65).Add();

                        col.Field("filePath").HeaderText("Doc. Path").TextAlign(TextAlign.Left).Width(65).Add();


                    })
                    )

as you can see , i have a cell called file path which should open a file upload dialog to upload file to server and  show the uploaded file path in the cell. 


Regards,
Sachin 

7 Replies

JK Jayaprakash Kamaraj Syncfusion Team January 18, 2017 12:38 PM UTC

Hi Sachin, 

Query1 : When i select a date from date picker  and move to another cell , i can't see the date which i selected in previous cell but when i save the data ,the date is getting passed to controller. Once the page is refreshed then it becomes visible , but during edit mode its not visible. 
 
We were unable to reproduce the issue at our end. Please share the following information to find the cause of the issue. 

1.     Share the video to show the issue. 
2.     Essential studio and browser version details. 
3.     Share your both client and server side code example. 
4.     Is there any script error or exception thrown in your project? If so, attach the screenshot of your stack trace.    
5.     If possible, provide an issue reproducing sample or hosted link or replicate the issue in the attached sample.   
 
 
Query 2: How to upload file when clicked on the grid cell in batch mode to server and display the file name on the cell,which can further be stored in database as file path. 
 
We can achieve your requirement using EditTemplate feature. We can render any control (Eg: uploadBox) in grid column while editing a row and also we can use all the features of that corresponding control by using editTemplate. In Write function we need to render ejUploadBox and then we need to change edited cell value in complete event of ejUploadBox. Please refer to the below help document, code example and sample. 
 
Help documents for, 
 
 
 
@(Html.EJ().Grid<object>("FlatGrid") 
.. 
                .Columns(col => 
               { 
.. 
                   col.Field("CustomerID").HeaderText("Customer ID").EditTemplate(a => { a.Create("create").Read("read").Write("write"); }).TextAlign(TextAlign.Right).Width(90.Add(); 
            .. 
 
              .ClientSideEvents(events=>events.CellEdit("onCellEdit").TemplateRefresh("TemplateRefresh")) 
) 
 
 
<script type="text/javascript"> 
    function create() { 
        return $("<div class='e-field'>"); 
    } 
 
    function write(args) { 
        var proxy = args; 
        args.element.ejUploadbox({ 
            saveUrl: "/Home/saveFiles", 
            extensionsAllow: ".zip", 
            complete: function (args) { 
                proxy.element.val(args.responseText); 
            }, 
              uploadName: "FlatGridEmployeeID", 
        }); 
        proxy.element.val(proxy.rowdata.CustomerID); 
    } 
 
    function read(args) { 
        return args.val(); 
    } 
 
</script> 
 
Homeontroller.cs 
 
public ActionResult saveFiles() 
        { 
            if (HttpContext.Request.Files.AllKeys.Any()) 
            { 
                var httpPostedFile = HttpContext.Request.Files["FlatGridEmployeeID"]; 
 
                if (httpPostedFile != null) 
                { 
                    if (httpPostedFile.FileName.Contains("\\")) 
                    { 
                        string[] pathArr = httpPostedFile.FileName.Split('\\'); 
                        fileName = pathArr.Last(); 
                    } 
                    else 
                        fileName = httpPostedFile.FileName; 
                    destination = Path.Combine(HttpContext.Server.MapPath("~/App_Data"), fileName); 
                    // To avoid unwanted storage in server we have commentted the below line 
                    httpPostedFile.SaveAs(destination); 
                } 
            } 
            return Content(destination); 
        } 
 
 
Regards, 
 
Jayaprakash K. 



SA sachin January 21, 2017 09:25 AM UTC

Hi Jayprakash,

Thanks for the response. your code solved my second issue and for the 1st i have captured a video of that error. The issue is with batch mode, if i add EditType(EditingType,DatePicker) in a column, then the date wont be visible once selected, i have also created a sample with this error.i hope these information will help you resolve this issue.
Apart from this i also need your help with following problems related to datepicker and dropdown.

  1. When i use datapicker on textbox and select a date , in textbox the date will be shown correctly but when the date is passed to controller action method its getting passed one less than the selected date (e.g- if selected date is 12/02/2016 then in controller itll be passed as 11/02/2016 ).
  2. How do i enable and disable the datepicker using external button. i tried this object.enable() but didn't work.  same thing i want to do with dropdown like initially they both should be disabled and when external button is clicked they should get enabled. how do i achieve this. 

Regards,
Sachin

Attachment: Thread128331_8121f571.7z


JK Jayaprakash Kamaraj Syncfusion Team January 23, 2017 01:10 PM UTC

 
Hi Sachin, 
 
Query 1:  if i add EditType(EditingType,DatePicker) in a column, then the date wont be visible once selected, i have also created a sample with this error.i hope these information will help you resolve this issue. 
 
We have analyzed your attached sample and found that the cause of issue is you have enabled dataPicker in String Column. If you set DataPicker in String column we can’t set formatted date in string column because we will get value as string not a Date object. But in our latest version date value will be display in string format in String column . 
 
Please upgrade to the new version that can be downloaded from the following link, 
 

Please follow the below steps. 
 
1)     Download and install the Essential Studio v14.4.0.20 .  
 
2)     Replace the Syncfusion scripts, CSS and DLL’s in your project from the following location. 
 
            Scripts and CSS: C:\Program Files (x86)\Syncfusion\Essential Studio\XX.X.X.XX\JavaScript\assets 
            Dlls: C:\Program Files (x86)\Syncfusion\Essential Studio\ XX.X.X.XX \Assemblies 
 
Here XX.X.X.XX denotes the product version(14.4.0.20). 
 
And also after upgrading please ensure to clear the browser cache to avoid accidental reference of the old scripts/CSS. 
 
please share the following information to serve you better    
 
1.     For what purpose you have enabled datePicker in String Column? 
Query 2: When i use datapicker on textbox and select a date , in textbox the date will be shown correctly but when the date is passed to controller action method its getting passed one less than the selected date (e.g- if selected date is 12/02/2016 then in controller itll be passed as 11/02/2016 ). 
The reported problem may occur due to the difference between web client and server timezones. To overcome this problem, you can set the timezone offset from UTC in hours using the ej.serverTimeZoneOffset which has been explained in the following Help Document.  
  
  
We suspect that your time zone is GST (UTC +4.0) which has been added to the client Timezone offset to retrieve the original dates. Refer to the following code example  


<script type="text/javascript">  
        var serverTimeZoneDiff = +4.0    
        var clientSideTimeZoneDiff = new Date().getTimezoneOffset() / 60; // get client time zone differents and convert it to hours;  
        ej.serverTimeZoneOffset = serverTimeZoneDiff + clientSideTimeZoneDiff;  
</script>  

Query 3: How do i enable and disable the datepicker using external button. i tried this object.enable() but didn't work.  same thing i want to do with dropdown like initially they both should be disabled and when external button is clicked they should get enabled. how do i achieve this. 
 
We can enable or disable the ejDataPicker and ejDropDown using enable  and disable methods of ejDataPicker and ejDropDown. Please refer to the below help documents, code example and sample. 
                     
Help document for, 
 
 
 

<input type="button" value="DataPicker Enable" onclick="DateEnable()" /><br /><br /> 
<input type="button" value="DataPicker Disbale" onclick="DateDisable()" /><br /><br /> 
<input type="button" value="DropDown Enable" onclick="DropDownEnable()" /><br /><br /> 
<input type="button" value="DropDown Disbale" onclick="DropDownDisable()" /><br /><br /> 
@Html.EJ().DatePicker("DatePick").EnablePersistence(true).Value(ViewBag.datevalue) 
@Html.EJ().DropDownList("selectCar").TargetID("carsList").Width("100%").WatermarkText("Select a Car") 
 
<script type="text/javascript"> 
    function DateEnable() { 
        var dateObj = $("#DatePick").data("ejDatePicker"); 
        dateObj.enable(); // enables the datepicker 
    } 
    function DateDisable() { 
        var dateObj = $("#DatePick").data("ejDatePicker"); 
        dateObj.disable(); // enables the datepicker 
    } 
    function DropDownEnable() { 
        var DropDownListObj = $("#selectCar").data("ejDropDownList"); 
        DropDownListObj.enable(); //Enables the DropDownList text. 
    } 
    function DropDownDisable() { 
        var DropDownListObj = $("#selectCar").data("ejDropDownList"); 
        DropDownListObj.disable(); //Hides the DropDownList text. 
    } 
</script> 

 
If we have misunderstood your requirement, then please the below details to analyze the issue.    
1.     In which scenario you want to disable/enable ejDatePicker and ejDropDown ? 
2.     share more details about your requirement 
Regards, 
 
Jayaprakash K. 



SA sachin February 2, 2017 07:46 AM UTC

Hi Jayprakash, 

Thanks for the solution . As you suggested i have updated my syncfusion and now datepicker is working fine with string datatype but i still was not able to solve the date difference issue as you said to use  serverTimeZoneOffset but somehow this is not working with batch grid if u can create a sample with this that would be a great help.   

Apart from this, i have some issue with the grid also.
  •  I am using grid with EditTemplate mode and have all the CRUD function in my controller. but when i add new row in the grid , it doesn't show after the successful addition unless i refresh the whole page. this is my controller 

 public ActionResult MasterDataSource(DataManager dm)
        {
            List<Model> result =result =getMasterList();                      
            IEnumerable data = result;
            int count = result.Count;
            DataOperations operation = new DataOperations();

            if (dm.Sorted != null && dm.Sorted.Count > 0) //Sorting
            {
                data = operation.PerformSorting(data, dm.Sorted);
            }
            if (dm.Where != null && dm.Where.Count > 0) //Filtering
            {
                data = operation.PerformWhereFilter(data, dm.Where, dm.Where[0].Operator);
            }
            if (dm.Search != null && dm.Search.Count > 0)
            {
                data = operation.PerformSearching(result, dm.Search);
            }
            count = data.Cast<Model>().Count();
            if (dm.Skip != 0)
            {
                data = operation.PerformSkip(data, dm.Skip);
            }
            if (dm.Take != 0)
            {
                data = operation.PerformTake(data, dm.Take);
            }

            return Json(new { result = data, count = count }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult MasterUpdate(Model value)
        {
            update(value);        
            return RedirectToAction("MasterDataSource");
        }

        public ActionResult MasterInsert(Model value)
        {
      insert(value);        
            return RedirectToAction("MasterDataSource");
        }

        public ActionResult MasterDelete(int key)
        {                    
            delete(key);      
            return RedirectToAction("MasterDataSource");
        }


and this is my grid 

  @(Html.EJ().Grid<MasterModel>("FlatGrid")
        .Datasource(ds => ds.URL(Url.Action("MasterDataSource", "CRUD", null, Request.Url.Scheme)).InsertURL(Url.Action("MasterInsert", "CRUD", null, Request.Url.Scheme)).UpdateURL(Url.Action("MasterUpdate", "CRUD", null, Request.Url.Scheme)).RemoveURL(Url.Action("MasterDelete", "CRUD", null, Request.Url.Scheme)).Adaptor(AdaptorType.UrlAdaptor))
        .EnableAltRow()
        .AllowFiltering()
        .AllowSorting()
        .GridLines(GridLines.Horizontal)

        .ContextMenuSettings(contextMenu =>
        {
            contextMenu.EnableContextMenu();

        })
         .PageSettings(page =>
         {
             page.PageSize(10);
         })
         .AllowTextWrap()
         .AllowResizeToFit()
         .EnableHeaderHover()
         .FilterSettings(filter => { filter.FilterType(FilterType.Excel); })
         .AllowPaging()
         .ClientSideEvents(eve =>
         {
             eve.ActionComplete("complete");
             eve.ActionFailure("failure");
             eve.RecordClick("recordClick");
             eve.RecordDoubleClick("recordDoubleClick");
             eve.ContextOpen("contextopen");
             eve.ContextClick("contextclick");
             eve.ActionBegin("beginAction");
             eve.Create("onGridCreate");
         })
         .ToolbarSettings(toolbar =>
         {
             toolbar.ShowToolbar().ToolbarItems(items =>
             {
                 items.AddTool(ToolBarItems.Search);
             });
         })
        .Columns(col =>
        {
            col.Field(p => p.ID).IsPrimaryKey(true).Visible(false).Add();
            col.Field(p => p.No).HeaderText("No").IsPrimaryKey(true).TextAlign(TextAlign.Left).Width(60).Add();
            col.Field(p => p.Desc).HeaderText("Description").Width(90).Add();
            col.Field(p => p.Inactive).HeaderText("Inactive").TextAlign(TextAlign.Left).Width(85).Add();

        })
                    )

As you can see i have used URL adapter as suggested. The MasterDataSource action is getting called every single time when i perform any CRUD operation but what i found is dm.Take is always 0 when new record is entered but when i refresh the whole page dm.Take value becomes more than 0 and i can see the inserted record. so i guess there is issue with the Take() method. Please help me how to solve this.

  •  I want to add two buttons on columns and add different click events , i tired Command function and added two buttons but this function only works on edit mode , when new record is added these button becomes too small see the attached image. So i tried to use column template which worked but the issue with this is the click events doesn't call controller action using ajax when there are multiple rows for single row it calls the action method. see the below code

      col.Field("filePath2").HeaderText("Document").Template("#buttonTemplate").Width(150).TextAlign(TextAlign.Center).Add();

<script id="buttonTemplate" type="text/x-jsrender">
    <button class="e-uploadbutton" id="uploadButton" type="button" value="upload"></button>
    <button class="e-downloadbutton" id="downloadButton" type="button" value="download"></button>
</script>

and i write the click event on cellEdit event

 function onDocCellEdit(args) {

             if (args.columnName == "filePath2") {

            $("#uploadButton").click(function(){
                        //ajax call                        
            });
           $("#downloadButton").click(function(){
                      //ajax call
            });
}
basically i want to call two different action method when the button is clicked and pass the ID of each row to the method. Please guide me how to achieve this either with template or command property. 

Regards
Sachin 


Attachment: issue_7a3ec4b5.rar


SS Seeni Sakthi Kumar Seeni Raj Syncfusion Team February 3, 2017 12:24 PM UTC

Hi Sachin, 
 
Query #1: date difference issue as you said to use serverTimeZoneOffset but somehow this is not working with batch grid 
 
We are sorry for the inconvenience. The reported problem is not occurred due to the Server Timezone different. The cause of the problem is due to the String column treated as the DateTime column. While parsing in the client end, JSON Parser vary the value. To overcome this problem, we suggest to parse the String (as DateTime) column in the server end. In the following code example, we have treated the CustomerID a string column as the Date column by rendering the DatePicker and parsed them at the server end. 
 
@(Html.EJ().Grid<object>("FlatGrid") 
               .Datasource(ds => ds.URL("/Grid/BatchData").BatchURL("/Grid/BatchUpdate").Adaptor(AdaptorType.UrlAdaptor)) 
       .AllowPaging()    /*Paging Enabled*/ 
           . . . . 
      .Columns(col => 
       { 
           col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(75).Add(); 
            //Assign DatePicker for String Column 
           col.Field("CustomerID").EditType(EditingType.Datepicker).HeaderText("Customer ID").Width(80).Add(); 
 
         }) 
    ) 
 
        public ActionResult BatchUpdate(string key, List<OrdersView> changed, List<OrdersView> added, List<OrdersView> deleted) 
        { 
            var Data = new NorthwindDataContext().OrdersViews; 
 
            if (added != null) 
            { 
                for (var add = 0; add < added.Count(); add++) 
                { 
                    /* Parse the string to Date 
                    * It will change to its original value 
                    * Since CustomerID is the string column 
                    * We cannot assign Parsed date back to original value 
                    */ 
                    DateTime dat = DateTime.Parse(added[add].CustomerID); 
                    Data.InsertOnSubmit(added[add]); 
                } 
            } 
            if (changed != null) 
            { 
                 . . . . 
            } 
            return Json(Data.ToList(), JsonRequestBehavior.AllowGet); 
        } 
 
Query #2: when i add new row in the grid , it doesn't show after the successful addition unless i refresh the whole page 
 
We are able to reproduce the problem at our end. Your previous updates states that you are using Batch Editing Mode but you have not defined the BatchUrl in the Adaptor which is the cause of the problem. To update the Batch Changes to the server end, you have to define the BatchURL. Refer to the following code example and Help document. 
 
@(Html.EJ().Grid<object>("FlatGrid") 
               .Datasource(ds => ds.URL("/Grid/BatchData").BatchURL("/Grid/BatchUpdate").Adaptor(AdaptorType.UrlAdaptor)) 
        .  . .. 
    ) 
 
 
Query #3: I want to add two buttons on columns and add different click events , i tired Command function and added two buttons but this function only works on edit mode , when new record is added these button becomes too small see the attached image. 
 
Since the Command buttons were not included as a editable column, the reported issue may occur. To overcome this problem, you can re-render the buttons in the BatchAdd event of the Grid. 
 
@(Html.EJ().Grid<object>("FlatGrid") 
 
      .Columns(col => 
       { 
           col.HeaderText("Add Values").Commands(command => 
           { 
              command.Type("detail") 
                 .ButtonOptions(new Syncfusion.JavaScript.Models.ButtonProperties() 
                    { 
                       Text = "Add", 
                       Width = "100px", 
                       Click = "onClick" 
                    }).Add(); 
             }) 
                .TextAlign(TextAlign.Left) 
               .Width(150) 
                .Add(); 
              . . . . 
         }) 
 
.ClientSideEvents(eve=>eve.BatchAdd("batchAdd")) 
    ) 
 
    function batchAdd(args){ 
        $(args.row).find(".e-detailbutton").ejButton({ 
            text: "ADD", height: "28px", width: "100px", 
            click: "onClick", 
            enable: false, htmlAttributes: { enabled: "enabled" } 
        }); 
    } 
 
Query #4: when the button is clicked and pass the ID of each row to the method 
 
In the click event of the command click, you can get the row details and data using the getIndexByRow and getCurrentViewData methods. Refer to the following code example and Help document. 
 
    function onClick(args) { 
        var obj = $("#FlatGrid").ejGrid("instance"); 
        var inx = obj.getIndexByRow(this.element.parents("tr")); 
        var rowdata = obj.getCurrentViewData()[obj.getIndexByRow(this.element.parents("tr"))]; 
    } 
 
 
We have modified our sample that can be downloaded from the following location. 
 
 
Regards, 
Seeni Sakthi Kumar S. 



SA sachin February 11, 2017 05:58 AM UTC

Hi Jayprakash,

Thanks for your prompt response, you have solved all my issues related to grid and i appreciate the support you have been providing me.

Regards,
Sachin 


JK Jayaprakash Kamaraj Syncfusion Team February 13, 2017 03:50 AM UTC

Hi Sachin, 
 
We are happy that the problem has been solved. 
 
Please get back to us if you need any further assistance.   
 
Regards, 
 
Jayaprakash K. 


Loader.
Up arrow icon