我的目标是让用户将文件上传到服务器,将文件保存在本地(在服务器上)并在模型中保留带有本地文件路径的属性,向用户返回不同的视图,然后返回到控制器/模型仍然具有文件路径的服务器。我的代码看起来像这样:
我的模型:
public class MyModel
{
public IFormFile MyFile { get; set; }
public string LocalFilePath { get; set; }
public void CopyFileLocally(ref string err)
{
try
{
var stream = System.IO.File.Create($"PathToSaveFile/{this.MyFile.FileName}");
stream.Position = 0;
this.DatFile.CopyTo(stream);
stream.Flush();
this.LocalFilePath = $"PathToSaveFile/{this.MyFile.FileName}";
}
catch (Exception ex)
{
err = ex.Message;
return;
}
}
}
我的控制器:
public class MyController
{
public IActionResult UploadFile(MyModel model)
{
string err = null;
model.CopyFileLocally(ref err);
if (err != null)
{
return Json(err);
}
return View("View2", model);
}
Public Void DoSomething(MyModel model)
{
// does something with model.LocalFilePath
}
}
意见:
View1:
@model MyModel
@using (Html.BeginForm("UploadFile", "MyController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<!---does a bunch of stuff and assigns a bunch of members--->
@Html.TextBoxFor(model => model.MyFile, null, new { @type = "file", @class = "input-file", @enctype = "multipart/form-data" })
<input type="submit" value="Send"/>
}
View2:
@model MyModel
@using (Html.BeginForm("DoSomething", "MyController", FormMethod.Post ))
{
<!-- does a bunch of stuff and creates a bunch of hidden TextBoxFor elements to reassign model properties including file name as seen below--->
@Html.TextBoxFor(model => model.LocalFilePath, new { @hidden = "hidden" })
<input type="submit" value="Send"/>
}
问题是一旦调用 DoSomething 函数,所有其他属性都被分配,只有 LocalFilePath 属性为空。知道为什么吗?