在Asp中上传文件.Net -异步控制器

本文关键字:异步 异步控制 控制器 Net 文件 Asp | 更新日期: 2023-09-27 18:13:58

所以我是net到ASP.net MVC,但不是新的c#。我在我的项目中链接了数据源,它创建了我所有的Create Read Update Delete方法和视图。太好了。现在我需要自定义一些东西。

首先,我需要上传一个。csv文件,它将填充我们的一个模型,作为我们从旧的笔和纸系统迁移的权宜之计。

这是当提交按钮被按下时调用的postback方法:

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "callout_id_pk,start_timestamp,drivers_license_needed,med_training_needed,worksite_code_fk,shift_notes,status,job_class_code_fk,worksite_name,job_class_name,gender_req")] Callout callout)
        {
            Debug.WriteLine("THIS LINE OF CODE RAN?");
            if (ModelState.IsValid)
            {
                db.Callouts.Add(callout);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }

            foreach (string upload in Request.Files)
            {
                if (Request.Files[upload].ContentLength == 0) continue;
                string pathToSave = Server.MapPath("~/App_Data/UploadedFiles");
                string filename = Path.GetFileName(Request.Files[upload].FileName);
                Request.Files[upload].SaveAs(Path.Combine(pathToSave, filename));
            }
            ViewBag.worksite_code_fk = new SelectList(db.Worksites, "worksite_code_pk", "worksite_name", callout.worksite_code_fk);
            return View(callout);
        }

这是视图,为了可读性,删除了不相关的控件。

@using (Html.BeginForm("Create", "Callouts", FormMethod.Post, new {enctype="multipart/form-data"})) 
{
    @Html.AntiForgeryToken()

        <!--@Html.ValidationSummary(true, "", new { @class = "text-danger" })-->
        <div class="form-group">
            <input type="file" name="FileUpload1" /><br />
        </div>
        <!-- other form controls here -->
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
}

现在,由于某些原因在回发中,请求。"文件"没有看到任何传回的文件。我遗漏了什么?注意,现在,我只是尝试将文件保存到磁盘。但是最后,文件将被读取并用于填充模型。

在Asp中上传文件.Net -异步控制器

答案真的很愚蠢。我的文件上传逻辑在一段代码下面,如果ModelState.IsValid()…