How to pass selected files in Kendo Upload as para

2019-09-20 08:00发布

问题:

After much of struggle im posing this question. Im using a Kendo Upload on a page. Am able to post the selected files on the asyn mode with whe the page has Html.BeginForm. But I'm not able to send file details as HttpPostedFileBase when I use ajax request to send data to the controller.

Following is my html

<form class="form-horizontal" role="form">
        <div class="form-group">
            @Html.Label("Complaint Name", new { @class = "col-sm-3 control-label" })
            <div class="col-sm-4">
                @Html.TextBoxFor(
                                 m => m.ComplaintName,
                                 new
                                     {
                                         @TabIndex = "1",
                                         @class = "form-control input-sm",
                                         disabled = true
                                     })
            </div>
        </div>
         <div class="form-group">
            @Html.Label("Complaint Details", new { @class = "col-sm-3 control-label" })
            <div class="col-sm-4">
                @Html.TextBoxFor(
                                 m => m.ComplaintDetails,
                                 new
                                     {
                                         @TabIndex = "2",
                                         @class = "form-control input-sm",
                                         disabled = true
                                     })
            </div>
        </div>
        <div class="form-group">
            @Html.Label("Choose files to upload", new { @class = "col-sm-3 control-label" })
            <div class="col-sm-9 nopaddingforTextArea">
                <input name="files" id="files" type="file" />
            </div>
        </div>
        <div class="form-group">
            <div>
                <input id="btnSubmit" class="btn btn-primary pull-right" type="button" />
            </div>
        </div>
</form>

Following is my action

public ActionResult SaveComplaintDetails(string complaintName, string complaintDetails, IEnumerable<HttpPostedFileBase> files)
{
}

Following is my js

$("#files").kendoUpload({
    async: {
        saveUrl: '@Url.Action("EsuperfundCommentsBind", ClientInboxConstants.NewQuery)',
        autoUpload: false
    },
    multiple: true
});

$("#btnSubmit").click(function () {
                            //Ajax call from the server side
                $.ajax({
                    //The Url action is for the Method FilterTable and the Controller PensionApplicationList
                    url: '@Url.Action("SaveComplaintDetails", "Complaints")',
                    //The text from the drop down and the corresponding flag are passed.
                    //Flag represents the Index of the value in the dropdown
                    data: {
                        complaintName: document.getElementById("ComplaintName").value,
                        complaintDetails: document.getElementById("ComplaintDetails").value,
                        files: //What to pass here??
                    },
                    contentType: "application/json; charset=utf-8",
                    //Json data
                    datatype: 'json',
                    //Specify if the method is GET or POST
                    type: 'GET',
                    //Error function gets called if there is an error in the ajax request
                    error: function () {
                    },
                    //Gets called on success of the Ajax Call
                    success: function (data) {

                    }
                });            
});

My question is how to pass the selected files in Kendo Upload in ajax as a parameter? Any help in this aspect would be really appreciated.

回答1:

If your view is based on a model and you have generated the controls inside <form> tags, then you can serialize the model to FormData using:

<script>
    var formdata = new FormData($('form').get(0));
</script>

This will also include any files generated with: <input type="file" name="myImage" .../> and post it back using:

<script>
    $.ajax({
        url: '@Url.Action("YourActionName", "YourControllerName")',
        type: 'POST',
        data: formdata,
        processData: false,
        contentType: false,
    });
</script>

and in your controller:

[HttpPost]
public ActionResult YourActionName(YourModelType model)
{
}

or (if your model does not include a property for HttpPostedFileBase)

[HttpPost]
public ActionResult YourActionName(YourModelType model, 
HttpPostedFileBase myImage)
{
}

If you want to add additional information that is not in the form, then you can append it using

<script>
    formdata.append('someProperty', 'SomeValue');
</script>


Example Usage :

View :

@using (Html.BeginForm("Create", "Issue", FormMethod.Post,
new { id = "frmCreate", enctype = "multipart/form-data" }))
{ 
    @Html.LabelFor(m => m.FileAttachments, new { @class = "editor-label" })
    @(Html.Kendo().Upload()
        .HtmlAttributes(new { @class = "editor-field" })
        .Name("files")
    )
}


<script>
$(function () { 
    $('form').submit(function (event) {
        event.preventDefault();            
        var formdata = new FormData($('#frmCreate').get(0)); 
        $.ajax({
            type: "POST",
            url: '@Url.Action("Create", "Issue")',
            data: formdata,
            dataType: "json",
            processData: false, 
            contentType: false, 
            success: function (response) {
                //code omitted for brevity
            }
        });  
    }); 
});
</script> 


Controller :

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = null)] Model viewModel, IEnumerable<HttpPostedFileBase> files)
{
    //code omitted for brevity
    return Json(new { success = false, message = "Max. file size 10MB" }, JsonRequestBehavior.AllowGet);
}

Hope this helps...



回答2:

<script>
$(function () {
    $('form').submit(function (event) {
        event.preventDefault();
        var formdata = new FormData($('#createDetail').get(0));
        $.ajax(
        {
            type: 'POST',
            url: '@Url.Action("Detail_Create", "Product")',
            data: formdata,
            processData: false,
            success: function (result) {

                if (result.success == false) {
                    $("#divErr").html(result.responseText);
                } else {
                    parent.$('#CreateWindowDetail').data('kendoWindow').close();
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                $("#divErr").html(xhr.responseText);
            }
        });
    });
});

@using (Html.BeginForm("Detail_Create", "Product", FormMethod.Post, new { id = "createDetail", enctype="multipart/form-data"}))
{
    <div id="divErr" class="validation-summary-errors"></div>
    <fieldset>
        <ol>
            <li>
                @Html.LabelFor(m => m.Price)
                @(Html.Kendo().NumericTextBoxFor(m => m.Price).Name("Price").Format("{0:0}")
                    .HtmlAttributes(new { style = "width:100%" })
                )
            </li>
            <li>
                @Html.LabelFor(m => m.Description)
                @Html.TextBoxFor(model => model.Description, new { @class = "k-textbox", id = "Description", style = "width:100%;" })
            </li>
            <li>
                @Html.LabelFor(m => m.Group)
                @(Html.Kendo().ComboBox()
                    .Name("Group")
                    .Placeholder("Введите группу детали")
                    .DataTextField("Name")
                    .DataValueField("Id")
                    .HtmlAttributes(new { style = "width:100%;" })
                    .Filter("contains")
                    .MinLength(1)
                    .DataSource(source =>
                    {
                        source.Read(read =>
                        {
                            read.Action("Group_Read_ComboBox", "Product");
                        })
                    .ServerFiltering(true);
                    })                
                )
            </li>
            <li>
                @Html.LabelFor(m => m.Image)
                @(Html.Kendo().Upload()
                    .Name("files")
                )
            </li>
        </ol>
    </fieldset>
    <button type="submit" id="get" class="k-button">Добавить</button>
}

[HttpPost]
        public ActionResult Detail_Create(DetailModel model, IEnumerable<HttpPostedFileBase> files)
        {
            string error = string.Empty;
            if (ModelState.IsValid)
            {
.....
            }
            IEnumerable<System.Web.Mvc.ModelError> modelerrors = ModelState.SelectMany(r => r.Value.Errors);
            foreach (var modelerror in modelerrors)
            {
                error += "&#8226;   " + modelerror.ErrorMessage + "<br>";
            }
            return Json(new { success = false, responseText = error }, JsonRequestBehavior.AllowGet);
        }

after pressing the button, the controller null comes to how to fix. 2 days already sitting, and the time comes to an end