淘汰赛:绑定上传的文件

时间:2016-09-20 19:27:50

标签: javascript jquery asp.net-mvc knockout.js

我遇到了无法从主淘汰视图模型中的嵌套模型上传多个文件的问题。

测试了上传HttpPostedFileBase属性,我使用XmlFile属性成功上传文件并在EditTestStepjs文件中使用两个同步ajax调用。

但是,在尝试发送绑定到列表中嵌套模型的多个文件时,我无法使用表单数据将其值发送到控制器。

嵌套视图模型

public class XmlParameterViewModel
{
    public string ParameterName { get; set; }
    public HttpPostedFileBase XmlValue { get; set; }
}

主视图模型

public class EditTestStepViewModel
{
    public string TestStepName { get; set; }
    public HttpPostedFileBase XmlFile { get; set; }
    public List<XmlParameterViewModel> XmlParameters { get; set; }

    public EditTestStepViewModel()
    {
        this.XmlParameters = new List<XmlParameterViewModel>();
    }

}

控制器

    [HttpPost]
    public ActionResult SaveEdit(EditTestStepViewModel editTestStepViewModel)
    {
        return View("Index", editTestStepViewModel);
    }

    public JsonResult FileUpload(List<HttpPostedFileBase> xmlFile)
    {
        return Json(new {success = true}, JsonRequestBehavior.AllowGet);
    }

EditTestStepJS文件

var EditTestStepViewModel = function(data) {
    var self = this;

    ko.validatedObservable(ko.mapping.fromJS(data, mapping, self));

    self.saveTestStep = function() {
        if (self.isValid()) {

            var file = new FormData($("#editForm").get(0));

            $.ajax({
                type: "POST",
                url: "/Home/FileUpload/",
                data: file,
                processData: false,
                contentType: false,
                dataType: "json",
                success: function () {

                    var dataToSend = ko.mapping.toJSON(self);
                    $.ajax({
                        url: "/Home/SaveEdit/",
                        type: "POST",
                        contentType: "application/json",
                        data: dataToSend
       });
     }
   });
 }
} 

查看

<form enctype="multipart/form-data" id="editForm">

 <table class="table table-striped">
        <tr>
            <th>XmlPara</th>
        </tr>

        <tbody data-bind="foreach: XmlParameters">
        <tr>
            <td class="form-group"> <input name="ParameterName" class="form-control input-sm" data-bind="value: ParameterName"  disabled="disabled"/></td>
            <td class="form-group"> <input name="XmlValue" type="file" class="btn btn-group" data-bind="value: XmlValue" /></td>
        </tr>
        </tbody>

    </table>
        <button data-bind="click: saveTestStep" type="submit">Save Test Step</button>

<form>

0 个答案:

没有答案