【问题标题】:Send Json object and file to controller with Javascript in MVC在 MVC 中使用 Javascript 将 Json 对象和文件发送到控制器
【发布时间】:2014-06-24 01:58:33
【问题描述】:

我有一个 Json 对象,例如:

  var appversion = { "Id": "", "Version": "", "HelpSystemId": "", "Content": "", "FileName": "", "IsLatest": "", "LastModify": "", "AppVersionChangsets": [] };
        appversion.Id = $("#Id").val();
        appversion.Version = $("#Version").val();
        appversion.HelpSystemId = $("#HelpSystemId").val();
        appversion.IsLatest = $("#IsLatest").val();
        appversion.LastModify = $("#LastModify").val();

还有一个我以这种方式获得的文件:

<div class="form-group">
        @Html.MyLabelFor(model => model.Content, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <input type="file" id="_file" name="_file" />
            <button onclick="abortRead();">Cancel read</button>
            <div id="progress_bar"><div class="percent">0%</div></div>
        </div>
    </div>

然后我将它发送给我的控制器:

 $.ajax({
          url: '/AppVersion/Create2',
          data: JSON.stringify(appversion),
          type: 'POST',
          contentType: 'application/json;',
          dataType: 'json',
         success: function (result) {
               if (result.Success == "1") {
                    window.location.href = "/AppVersion/index";
               }
               else {
                   alert(result.ex);
               }
           }});

控制器是:

    [HttpPost]
    [AcceptVerbs(HttpVerbs.Post)]
    public JsonResult Create2(AppVersion appversion)
    {
    //Some Code
    }

我的问题是我无法访问控制器中的文件。我只是得到我的 json 对象。如何将带有 Json 对象的文件发送到控制器?

  if (Request.Files["file"].ContentLength > 0)
                {
                    Stream str = Request.Files["file"].InputStream;
                    byte[] data = new byte[str.Length];
                    str.Read(data, 0, System.Convert.ToInt32(str.Length));
                }

【问题讨论】:

  • 您是否将身份验证@Controller 放在您的控制器上?
  • 还没有。没有为我的控制器设置身份验证
  • 尝试将@Controller 放在您的控制器上,并确保您的控制器正在执行。
  • 如何将带有 Json 对象的文件发送到控制器,您的意思是如何将 json 对象发送到控制器或什么?
  • 你能给我一个例子的链接吗?

标签: javascript json file asp.net-mvc-4 send


【解决方案1】:

有一个名为'ajaxfileupload'的Jquery插件,也许你可以使用它。 网址是“http://www.phpletter.com/Demo/AjaxFileUpload-Demo/”。

【讨论】:

  • 我用js搜索上传文件,发现很多这样的答案。他们工作得很好。但我想一起发送 json 对象和文件。如果我发送其中一个它可以工作,但我想要两个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-09
  • 1970-01-01
  • 2014-03-01
  • 2014-10-20
  • 2014-10-31
  • 1970-01-01
相关资源
最近更新 更多