Async kendoUpload pass custom arguments or additional data to MVC Controller

13 posts, 0 answers
  1. Ismael
    Ismael avatar
    2 posts
    Member since:
    Aug 2012

    Posted 17 Aug 2012 Link to this post

    I needed to pas an id to the async upload control. i'm using MVC, c# and razor engine.

    Solution:
    All that's needed it to define a function for the upload event and modify the "data" payload.

    Now on the server side i got my id to associate the file on the DB.

    HTML:
            <div>
                <input name="files" id="files" type="file" />            
            </div>

    JScript:
            $("#files").kendoUpload({
                async: {
                    saveUrl: '@Url.Action("Save", "Codes")',
                    removeUrl: '@Url.Action("Remove", "Codes")',
                    autoUpload: true
                },
                upload: function (e) {
                    e.data = { codeID: $("#id").val() };
                }

            });

    Controller:
            [HttpPost]
            public ActionResult Save(IEnumerable<HttpPostedFileBase> files, Guid codeID)
            {
                // The Name of the Upload component is "attachments" 
                foreach (var file in files)
                {
                    // Some browsers send file names with full path. This needs to be stripped.
                    var fileName = Path.GetFileName(file.FileName);
                    var physicalPath = Path.Combine(Server.MapPath("~/Content/files"), fileName);

                    file.SaveAs(physicalPath);
                }
                // Return an empty string to signify success
                return Content("");
            }
  2. Scott
    Scott avatar
    68 posts
    Member since:
    Nov 2011

    Posted 28 Aug 2012 Link to this post

    i need an answer to this as well....?
  3. Kendo UI is VS 2017 Ready
  4. Ismael
    Ismael avatar
    2 posts
    Member since:
    Aug 2012

    Posted 28 Aug 2012 Link to this post

    Actually this works for me now, i wanted to put the code out there for anyone looking for the same thing but probably posted it wrong.

    Solution:
    All that's needed it to define a function for the upload event and modify the "data" payload.

    HTML:
            <div>
                <input name="files" id="files" type="file" />            
            </div>

    Add the upload JS function to add a parameter "codeID" in my case.
    JScript:
            $("#files").kendoUpload({
                async: {
                    saveUrl: '@Url.Action("Save", "Codes")',
                    removeUrl: '@Url.Action("Remove", "Codes")',
                    autoUpload: true
                },
                upload: function (e) {
                    e.data = { codeID: $("#id").val() };
                }

            });

    Now on the controller add the parameter and that's it.
    Controller:
            [HttpPost]
            public ActionResult Save(IEnumerable<HttpPostedFileBase> files, Guid codeID)
            {
              
            } 

  5. Luc
    Luc avatar
    12 posts
    Member since:
    Dec 2007

    Posted 13 Nov 2012 Link to this post

    Much appreciated Ismael
  6. im
    im avatar
    27 posts
    Member since:
    Mar 2012

    Posted 07 Dec 2012 Link to this post

    This does work, however how can you get data from the grid to populate that extra variable.

      upload: function (e) {
                    e.data = { codeID: $("#id").val() };
                }


    I need to grab a field from within the grid to populate the #id field. 
  7. jose
    jose avatar
    8 posts
    Member since:
    Apr 2012

    Posted 26 Dec 2012 Link to this post

    Just in case someone uses the server wrappers
    model ProjectName.Models.MyViewModel

    @Html.LabelFor(model=>model.Id)
    @Html.EditorFor(model=>model.Id)
    @(Html.Kendo().Upload()
            .Name("attachments")
            .Async(async => async
            //.Save("Save", "Grid")//either way....
            .SaveUrl(@Url.Action("Save", "Grid"))
            .AutoUpload(true)
            

            ).Events(e => e
                .Upload(@<text>
                function(e) {    
                 e.data = { id: $("#Id").val() };
                }
              </text>)
            )
    )
      [HttpPost]
            public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments,string id)
            {
                // The Name of the Upload component is "attachments"
                foreach (var file in attachments)
                {

                }

                // Return an empty string to signify success
                return Content("");


            }
  8. Mark Mergler
    Mark Mergler avatar
    10 posts
    Member since:
    Feb 2010

    Posted 03 Jun 2013 Link to this post

    Great thanks
  9. Mukul
    Mukul avatar
    5 posts
    Member since:
    Nov 2011

    Posted 01 Aug 2013 Link to this post

    Hi,

    Is it possible to send a model object/complex object and not just simple primitives as data object of upload event of KendoUpload and access the same in controller's action method? I always get null value on controller action if i try sending any object with multiple properties.
    Is this a bug/shortcoming of Kendo Upload control? Please let me know if you have a solution for the same.

    As long as I send simple entries like multiple strings etc., each one of them is accessible on the controller action. But when I try to send a complex object like the model as a whole or creating JSON string, I only get null value for object on the controller action method.

    I have to send a good number of fields to associate with the file as its metadata information. So, it will be cleaner for me if I could send the whole model object as additional data to async upload control and subsequently access the same in the controller action handling file save operation.

    I am using MVC3 with Razor, C#. Following is my brief code structure, for reference:

    Controller Action and Model class :
    [HttpPost]
            public ActionResult UploadFile(IEnumerable<HttpPostedFileBase> files, AzureUploaderModel uploader) 
            {
                //Removing internal code for brevity. I should be able to get a data filled 'uploader' at this point and not null.
     
                // Return an empty string to signify success
                return Content("");
            }
    public class AzureUploaderModel
        {
            public string AzureAccountName { get; set; }       
            public string AzureAccountKey { get; set; }
            public string ContainerName { get; set; }
            public String ContainerFilterId { get; set; }
        }

    View code:

    <input name="files" id="upload" type="file"/>
     $("#upload").kendoUpload({
                template: kendo.template($('#fileTemplate').html()),
                async: {
                    saveUrl: '@Url.Action("UploadFile", "AzureUpload")',
                    removeUrl: '@Url.Action("Remove", "AzureUpload")',
                    autoUpload: false
                },
                upload: onUpload
            });

    ONUPLOAD -try1

    function onUpload(e) {
                    e.data = { uploader: '@Model'};  }

    ONUPLOAD -try2

    function onUpload(e) {
                var uploader = {
                        AzureAccountName: $("#AzureAccountName").val(),
                        AzureAccountKey: $("#AzureAccountKey").val(),
                        ContainerName: $("#ContainerName").val()
                };
                    //  var postData = JSON.stringify(uploader);                
                    e.data = { uploader: uploader};   //postData };
            }

  10. Scott
    Scott avatar
    68 posts
    Member since:
    Nov 2011

    Posted 01 Aug 2013 Link to this post

    To pass multiple arguments to my MVC controller method... this is what I did....

    Here is the controller method:

    public ActionResult UploadFiles(IEnumerable<HttpPostedFileBase> files, string importType, string adjustmentType, string notes, Nullable<DateTime> transactionDate)
    {
         ...... code deleted for brevity ......
    }

    Javascript:

    function onUpload(e)
    {
        e.data =
            {
                importType: $("input[id^='ImportType-']:checked").val(),
                adjustmentType: $("input[id^='AdjustmentType-']:checked").val(),
                notes: $("#NotesTextArea").val(),
                transactionDate: $("#TransactionDate_wrapper").val()
            };
    }

    I never tried putting all these into one object on the server side, so don't know if
    ASP.NET MVC would assign correctly.... but the above example does what i need
    it too... ENJOY!!! :)
  11. Mukul
    Mukul avatar
    5 posts
    Member since:
    Nov 2011

    Posted 02 Aug 2013 Link to this post

    That is exactly what I am doing to make it work for the time being.
    But I was hoping somebody may be aware of a cleaner solution to this which utilizes the power of MVVM, since I need at least 8 parameters for each file to be set on client side and to be stored as file's metadata from the server.
  12. Dimiter Madjarov
    Admin
    Dimiter Madjarov avatar
    2156 posts

    Posted 05 Aug 2013 Link to this post

    Hi Mukul,


    I answered this question in the support ticket, but I will post a quote here too, if someone else requires assistance on the topic.


    Yes it is possible to pass objects or collections as additional data in the upload event. A sample approach would be to stringify the C# model and then parse it to convert it to a JavaScript object.
    E.g.
    function upload(e) {
        var additional = '@Html.Raw(Json.Encode(Model))';
        e.data = JSON.parse(additional);
    }

    Then in the Controller Action you could get the model as additional parameter.
    E.g.
    public ActionResult Save(IEnumerable<HttpPostedFileBase> files, ModelType additional)
    { }


     

    Regards,
    Dimiter Madjarov
    Telerik
    Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
  13. yi
    yi avatar
    3 posts
    Member since:
    Jun 2014

    Posted 26 Sep 2014 in reply to Dimiter Madjarov Link to this post

    i dont think kendo has the ability to support what you said.
  14. Dimiter Madjarov
    Admin
    Dimiter Madjarov avatar
    2156 posts

    Posted 26 Sep 2014 Link to this post

    Hi Yi,


    If you are experiencing any issues, please provide further details about the current case, so I could assist with it.

    Regards,
    Dimiter Madjarov
    Telerik
     
    Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
     
Back to Top
Kendo UI is VS 2017 Ready