我正在尝试使用包含在 ViewModel 中的指定 batchId 参数转到 View ,选择要上传的文件,取回上传的文件并将文件数据与相关的 BatchId 值存储在数据库中。
提交表单后,我不知道如何取回 View 模型和 PostedFileBase 以便我可以获得 BatchId 值。
我需要 batchId 值将其与我存储在数据库中的数据相关联。
我的 Controller 中有以下操作方法,允许通过文件上传和导入将新客户添加到指定批处理:
public ActionResult AddCustomers(int batchId)
{
var viewModel = new AddCustomersViewModel() { BatchId = batchId, //other view model properties };
return View(viewModel);
}
我的 View 是针对该 ViewModel 的强类型:
Inherits="System.Web.Mvc.ViewPage<TestExcelImport.Areas.Admin.ViewModels.AddCustomersViewModel>
并具有以下文件上传功能:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>AddCustomers Batch ID : <%:Model.BatchId %></h2>
<form action="/Admin/Dashboard/AddCustomers" enctype="multipart/form-data" method="post">
<input type="file" id="SourceFile" name="SourceFile" />
<br />
<input type="submit" value="Send" name="btnUpload" id="Submit1" />
</form>
</asp:Content>
我的 HttpPost 操作方法定义为:
[HttpPost]
public ActionResult AddCustomers(HttpPostedFileBase SourceFile)
{
//int batchId = ??? HOW DO I Get the BatchId
int fileLength = SourceFile.ContentLength; //works!
// read through SourceFile.InputStream and store it in db
//need the associated BatchID though
return RedirectToAction("Index");
}
我尝试在 HttpPost 返回方法参数列表中添加一个 AddCustomersViewModel,但它始终为 null。我可以很好地读取/解析上传的文件,只是无法取回它属于哪个 BatchId。
有人看到我做错了什么吗?
谢谢
最佳答案
虽然有多种方法可以实现您想要的效果,但我会推荐如下方法(因为它是最简单的):
将您的操作方法签名更改为:
public ActionResult AddCustomers(int BatchID, HttpPostedFileBase SourceFile)
并将呈现的 View 更改为:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>AddCustomers Batch ID : <%:Model.BatchId %></h2>
<form action="/Admin/Dashboard/AddCustomers" enctype="multipart/form-data" method="post">
<input type="hidden" value="<%: Model.BatchId %>" id="BatchID" name="BatchID" />
<input type="file" id="SourceFile" name="SourceFile" />
<br />
<input type="submit" value="Send" name="btnUpload" id="Submit1" />
</form>
</asp:Content>
这可确保您的 BatchId 值与文件一起来回传输。
更高级的解决方案(如果这不符合您的需求)可能包括:
- 在表单发布到的 URL 中添加 BatchId。
- 使用 session 状态来存储 ID。
关于ASP.Net MVC 文件上传后置参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3604225/