首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将Kendo上传中的选定文件作为参数传递到ajax请求中

如何将Kendo上传中的选定文件作为参数传递到ajax请求中
EN

Stack Overflow用户
提问于 2016-02-03 13:38:57
回答 2查看 5.7K关注 0票数 2

经过很大的努力,我提出了这个问题。我在页面上使用Kendo的上传。当页面有Html.BeginForm时,能够在asyn模式下发布所选的文件。但是,当我使用ajax请求向控制器发送数据时,我无法以HttpPostedFileBase的形式发送文件细节。

以下是我的html

代码语言:javascript
运行
复制
<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>

以下是我的行动

代码语言:javascript
运行
复制
public ActionResult SaveComplaintDetails(string complaintName, string complaintDetails, IEnumerable<HttpPostedFileBase> files)
{
}

以下是我的js

代码语言:javascript
运行
复制
$("#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) {

                    }
                });            
});

我的问题是如何将Kendo中选定的文件作为参数传递给ajax?在这方面的任何帮助都将是非常感谢的。

EN

回答 2

Stack Overflow用户

发布于 2016-02-04 11:45:26

如果您的视图基于模型,并且在<form>标记中生成了控件,则可以使用以下方法将模型序列化为FormData:

代码语言:javascript
运行
复制
<script>
    var formdata = new FormData($('form').get(0));
</script>

这还将包括使用:<input type="file" name="myImage" .../>生成的任何文件,并使用以下方法将其发回:

代码语言:javascript
运行
复制
<script>
    $.ajax({
        url: '@Url.Action("YourActionName", "YourControllerName")',
        type: 'POST',
        data: formdata,
        processData: false,
        contentType: false,
    });
</script>

在你的控制器里:

代码语言:javascript
运行
复制
[HttpPost]
public ActionResult YourActionName(YourModelType model)
{
}

或者(如果模型不包括HttpPostedFileBase的属性)

代码语言:javascript
运行
复制
[HttpPost]
public ActionResult YourActionName(YourModelType model, 
HttpPostedFileBase myImage)
{
}

如果要添加未在窗体中的其他信息,则可以使用

代码语言:javascript
运行
复制
<script>
    formdata.append('someProperty', 'SomeValue');
</script>

示例用法:

意见:

代码语言:javascript
运行
复制
@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> 

主计长:

代码语言:javascript
运行
复制
[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);
}

希望这能帮上忙。

票数 1
EN

Stack Overflow用户

发布于 2016-04-08 22:54:12

代码语言:javascript
运行
复制
<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);
            }
        });
    });
});

代码语言:javascript
运行
复制
@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);
        }

按下按钮后,控制器null将讨论如何修复。坐了两天,时间就到了。

票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35178662

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档