从 jquery 调用 knockout viewmodel 函数

Call knockout viewmodel function from jquery

我知道已经有几个类似的问题了,但是 none 帮助解决了我的问题。

我正在尝试使用 ajax post 和 return 上传一个包含文件描述的 json 的文件,然后将其传递给一个 knockout viewmodel 函数在我的 .js 文件中。

我可以使用 ajax post:

上传文件
     $('.upload-button').click(function () {
        var formData = new FormData();
        var file = document.getElementById("fileupload").files[0];
        formData.append("FileUpload", file);
        var action = "/QuestionWizard/Upload";

        $.ajax({
            type: "POST",
            url: action,
            data: formData,
            contentType: false,
            processData: false,
            success: function (result) {
                //call viewmodel function here and pass result
            }
        });
    });

这是我的视图模型函数:

      var ViewModel = function (d, m) {
        var self = this;
        var formData = null;

        self.Model = ko.mapping.fromJS(d, m);



        self.AddDoc = function (data) {
            self.Model.CurrentStep().Files.push({ Name: data.Name, Extension: data.Extension, ContentType: data.ContentType, Size: data.Size, Content: data.Content, FilePath: data.FilePath, Folder: data.Folder });
        }

    }

上传操作:

 [HttpPost]
    public JsonResult Upload() {
        FileUploadModel upload = new FileUploadModel();

        try {

            if (Request.Files != null) {
                HttpPostedFileBase file = Request.Files[0];
                upload.Size = settings.ConvertBytesToMegabytes(file.ContentLength);

                using (var binaryReader = new BinaryReader(Request.Files[0].InputStream)) {
                    upload.Content = binaryReader.ReadBytes(Request.Files[0].ContentLength);
                }

                upload.Name = Path.GetFileName(Request.Files[0].FileName);
                upload.ContentType = Request.Files[0].ContentType;
                upload.Extension = Path.GetExtension(Request.Files[0].FileName);
                upload.Folder = User.Question + "-" + User.Token;
                Transmit.write(ref upload);
            }
        } catch (Exception) {
            return Json(null);
        }
        return Json(upload);
    }

视图中的上传按钮:

 <input type="file" name="fileupload" id="fileupload" data-bind="event:{ change: Upload.bind($data, $element.files[0]) }" />

谁能帮我弄清楚如何调用 viewmodel 函数并传递结果 json 或更好的方法。

谢谢。

您只需将 AJAX 移动到视图模型所在的范围内。例如,我通常将我的 Knockout 代码构造为:

var Namespace = Namespace || {};

Namespace.AppName = (function () {
    var _init = function (data) {
        var viewModel = Namespace.AppName.ViewModel(data);
        ko.applyBindings(viewModel);
        _wireEvents(viewModel);
    };

    var _wireEvents = function (viewModel) {
        // using the example of your AJAX method
        $('.upload-button').click(viewModel.DoUpload);
    };

    return {
        Init: _init
    };
})();

然后,要连接所有内容,您只需在您的视图中执行以下操作:

$(document).ready(function () {
    var data = {}; // any initial data you feed into the view model
    Namespace.AppName.Init(data);
});

由于 .upload-button 单击处理程序实际上调用了视图模型上的方法,因此您可以直接访问它。例如,在您的视图模型定义中:

self.DoUpload = function () {
    ...

    $.ajax({
        type: "POST",
        url: action,
        data: formData,
        contentType: false,
        processData: false,
        success: function (result) {
            // use `self` to access any view model observable
        }
    });
};