所以我是ASP.net MVC的网络,但不是C#的新手。我已将我的项目与数据源链接,并创建了所有的Create Read Update Delete方法和视图。大。现在我需要定制一些东西。
首先,我需要上传一个.csv文件,这将填充我们的一个模型,作为我们从旧的纸笔系统迁移时的权宜之计。
这是在按下提交按钮时调用的回发方法:
[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>
}
现在,由于某些原因在回发中,Request.Files没有看到任何文件回发。我在这里错过了什么?请注意,目前,我只是想将文件保存到磁盘。但最后,该文件将被读取并用于填充模型。
答案 0 :(得分:0)
答案结果证明是愚蠢的。我的文件上传逻辑低于一大块代码,如果是ModelState.IsValid()......那么就称为'return'。