This is a migrated thread and some comments may be shown as answers.

Kendo grid EditorTemplate Uploader not working with Grid's Update

1 Answer 772 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Kelum
Top achievements
Rank 2
Kelum asked on 11 Feb 2021, 01:11 AM

I just created the following grid with kendo EditorTemplate

https://i.stack.imgur.com/f8RbA.png

this is the code snippet for this grid

@(Html
                    .Kendo()
                    .Grid<SampleModel>()
                    .Name("sampleGrid")
                    .Columns(columns =>
                    {
                        columns.Bound(p => p.Name);                            
                        columns.Bound(p => p.Logo).ClientTemplate("<img src='data:image/png;base64,#=Logo#' style='height: 100px; width: auto' />").EditorTemplateName("LogoFile");
                        columns.Command(p =>
                        {     
                            p.Edit();
                            p.Destroy();
                        });
 
                    })
                    .ToolBar(t =>
                    {
                        t.Create();
                    })
                    .Pageable()
                    .Sortable()
                    .Scrollable()
                    .Filterable()      
                    .AutoBind(true)
                    .DataSource(dataSource => dataSource
                        .Ajax()
                        .Model(m =>
                        {
                            m.Id(mr => mr.Id);
                        })
                        .PageSize(20)
                        .Create(cr => cr.Action("Create", "Sample"))
                        .Read(read => read.Action("Read", "Sample"))
                        .Update(upd => upd.Action("Update", "Sample").Data("setUpdateValues"))
                        .Destroy(dest => dest.Action("Delete", "Sample"))
                    )
                    .Events(e => e.Change("setUpdateValues"))
        )


This is working properly for View Objects and Add new Objects but for the Update scenario, it's not hit the backend method if update only the image file. if the Name property changes then it's hit backend.

https://i.stack.imgur.com/Z5IfK.png

 
this is my model

public class SampleModel
{
    public int Id { get; set; }
     
    public string Name { get; set; }
 
    public string Logo { get; set; }
  
}



This is the Editor template

@model string    
@(Html.Kendo()
        .Upload()
        .Name("LogoFile")
        .ShowFileList(true)
        .Events(events =>
        {  events.Select("onSelect");
            events.Success("onUploadSuccess");
        })
        .Messages(messages =>
        {
            messages.Select("Select Logo Picture");
        })
        .Async(async =>
        {
            async.Save("SaveFile", "Sample");
            async.Remove("DeleteFile", "Sample");
            async.AutoUpload(true);
        })
        .Multiple(false)
        .HtmlAttributes(new { data_value_primitive = "true" })
        .Validation(validation => validation
        .AllowedExtensions(new string[] { ".jpeg", ".jpg", ".png" })
        .MaxFileSize(1000000)))

 

this is the script section in the above .cshtml file

@section ViewSpecificJavascript {
    <script type="text/javascript">
 
        function setUpdateValues() {
  
            var obj =
            {
                Name: $("#Name").val(),
                Logo: $("#Logo").val()
            };
            return obj;
        }
 
        function onSelect(e) {
 
            var fileInfos = e.files;
            var wrapper = this.wrapper;
 
            fileInfos.forEach(function (fileInfo) {
                addPreview(fileInfo, wrapper);
            });
        }
        function addPreview(file, wrapper) {
             var raw = file.rawFile;
             var reader = new FileReader();
 
            if (raw) {
                reader.onloadend = function (e) {
                var preview = $("<img class='image-preview'>").attr("src", this.result);
                wrapper.find(".k-file[data-uid='" + file.uid + "'] .k-file-extension-wrapper").replaceWith(preview);
            };
               reader.readAsDataURL(raw);
             
        }
    }; 
 
        function onUploadSuccess(e) {
            switch (e.response.Type.toString().toLowerCase()) {
                case "upload": paint: alert('Your logo file has been uploaded successfully.'); break;
                case "remove": alert('Your logo file has been removed successfully.'); break;
            }
        }
 
 
    </script>   
 }



even this setUpdateValues javascript method calls, if I change the Name model property value, but it's not even hit If I change only the photo.

This is my backend method

public ActionResult Update(SampleModel obj)
    {
        ....
 
        return Json(new { success = true });
    }


What did I miss here, even I tried to change this Logo value like this $("#Logo").val("TEST"), just thought this is because this model identifies as not changed, but the same result still not calling.

This is the Stackoverflow question

1 Answer, 1 is accepted

Sort by
0
Patrick | Technical Support Engineer, Senior
Telerik team
answered on 12 Feb 2021, 11:39 PM

Hello Kelum,

One way in which you could use the Kendo UI Grid with the Kendo UI Upload Editor template is use a hidden input to set the new value of the Logo property:

LogoFile.cshtml

@model string

<script>
    function onUploadSuccess(e) {

        // The ImageUrl property is updated by setting a new value to the hidden input and triggering change.
        //The file will remain uploaded elsewhere
        var fileName = e.files[0].name;
        $("#Logo").val(fileName);
        $("#Logo").trigger("change");
    }
</script>

<input type="hidden" name="Logo" id="Logo" />

@(Html.Kendo()
        .Upload()
        .Name("LogoFile")
        .ShowFileList(true)
        .Events(events =>
        {  
            //events.Select("onSelect");
            events.Success("onUploadSuccess");
        })
        .Messages(messages =>
        {
            messages.Select("Select Logo Picture");
        })
        .Async(async =>
        {
            async.Save("Async_Save", "Grid");
            async.Remove("Async_Remove", "Grid");
            async.AutoUpload(true);
        })
        .Multiple(false)
        .HtmlAttributes(new { data_value_primitive = "true" })
        .Validation(validation => validation
        .AllowedExtensions(new string[] { ".jpeg", ".jpg", ".png" })
        .MaxFileSize(1000000)
        )
)

 

Following the above, the records are saved including the string Logo field using the Update action method:

Grid

@(Html.Kendo().Grid<GridExample.Models.SampleModel>()
    .Name("Grid")
    .Columns(columns => {
        columns.Bound(p => p.Name);
        columns.Bound(p => p.Logo).ClientTemplate("<img src=\"Images/#=Logo#\" style='height: 100px; width: auto' />").EditorTemplateName("LogoFile");
        columns.Command(command => { command.Edit(); command.Destroy(); }).Width(250);
    })
    .ToolBar(toolbar => {
        toolbar.Create();
    })
    .Height(550)
    .Editable(editable => editable.Mode(GridEditMode.InLine))
    .Pageable()
    .Sortable()
    .Scrollable()
    .Filterable()
    .AutoBind(true)
    .Events(events => events.Sort("onSort"))
    .DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(20)
        .Events(events => events.Error("error_handler"))
        .Model(model => model.Id(p => p.Id))
        .Create("Create", "Grid")
        .Read("Read", "Grid")
        .Update("Update", "Grid")
        .Destroy("Delete", "Grid")
    )
)

Update Action Method

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Update([DataSourceRequest] DataSourceRequest request, SampleModel sample)
        {
            if (sample != null && ModelState.IsValid)
            {
                var entity = new SampleModel();

                entity.Id = sample.Id;
                entity.Name = sample.Name;
                entity.Logo = sample.Logo;

                db.Samples.Attach(entity);
                db.Entry(entity).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();       
            }

            return Json(new[] { sample }.ToDataSourceResult(request, ModelState));
        }

I hope this information helps regarding a way to add a Kendo UI Upload as an Editor Template.   

Regards,
Patrick
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

Tags
Grid
Asked by
Kelum
Top achievements
Rank 2
Answers by
Patrick | Technical Support Engineer, Senior
Telerik team
Share this question
or