Async kendoUpload pass custom arguments or additional data to MVC Controller

2 Answers 8383 Views
Upload
Ismael
Top achievements
Rank 1
Ismael asked on 18 Aug 2012, 03:28 AM
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("");
        }
Scott
Top achievements
Rank 2
commented on 28 Aug 2012, 06:28 PM

i need an answer to this as well....?

2 Answers, 1 is accepted

Sort by
0
Ismael
Top achievements
Rank 1
answered on 28 Aug 2012, 10:33 PM
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)
        {
          
        } 

Luc
Top achievements
Rank 1
commented on 13 Nov 2012, 12:33 PM

Much appreciated Ismael
im
Top achievements
Rank 2
commented on 07 Dec 2012, 09:21 PM

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. 
jose
Top achievements
Rank 1
commented on 27 Dec 2012, 02:37 AM

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("");


        }
Mark Mergler
Top achievements
Rank 1
commented on 03 Jun 2013, 11:01 AM

Great thanks
Mukul
Top achievements
Rank 1
commented on 01 Aug 2013, 07:13 AM

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 };
        }

Scott
Top achievements
Rank 2
commented on 01 Aug 2013, 02:35 PM

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!!! :)
Mukul
Top achievements
Rank 1
commented on 02 Aug 2013, 06:47 AM

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.
0
Dimiter Madjarov
Telerik team
answered on 05 Aug 2013, 06:53 AM
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!
yi
Top achievements
Rank 1
commented on 26 Sep 2014, 10:56 AM

i dont think kendo has the ability to support what you said.
Dimiter Madjarov
Telerik team
commented on 26 Sep 2014, 11:03 AM

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!
 
Tags
Upload
Asked by
Ismael
Top achievements
Rank 1
Answers by
Ismael
Top achievements
Rank 1
Dimiter Madjarov
Telerik team
Share this question
or