ASP.Net MVC 文件上传POST参数

4
我正在尝试通过ViewModel打包指定的batchId参数并进入一个视图,选择要上传的文件,获取已上传的文件并将文件数据与相关的BatchId值存储在数据库中。
当提交表单时,我不知道如何获取ViewModel和PostedFileBase以便获取BatchId值。
我需要BatchId值来将其与我存储在数据库中的数据关联起来。
我在我的控制器中有以下操作方法,允许通过文件上传和导入来添加新客户到指定的批次:
public ActionResult AddCustomers(int batchId)
{
    var viewModel = new AddCustomersViewModel() { BatchId = batchId, //other view model properties };
        return View(viewModel);
}

我的视图与该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,但它总是为空。我可以很好地读取/解析上传的文件,只是无法获取它属于哪个BatchId。

有人看出我做错了什么吗?

谢谢

1个回答

7
虽然有很多方法可以实现你想要的功能,但我建议使用以下方式(因为它是最简单的):
将你的操作方法签名更改为:
public ActionResult AddCustomers(int BatchID, HttpPostedFileBase SourceFile) 

将渲染视图更改为:

<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值与文件一起传输。
如果这种方式无法满足您的需求,更高级的解决方案可能包括:
  • 将BatchId添加到表单提交的URL中。
  • 使用会话状态存储ID。

1
非常感谢,那个方法很有效。我有点困惑参数如何映射回来。在post方法中是否可能将整个viewModel返回?我觉得我的困惑开始是因为我看到的大多数示例都是使用HtmlHelper扩展方法进行表单提交,但由于我在代码中使用文件上传,所以使用HtmlHelpers让我感到困惑。 - jrob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接