【问题标题】:MVC 5 Uploading file (POST) with one additional parameter带有一个附加参数的 MVC 5 上传文件 (POST)
【发布时间】:2017-10-18 16:58:14
【问题描述】:

我正在使用this 简单教程在我的 MVC5 C# VS2015 项目中上传文件,并且在控制器操作中不需要其他参数,文件会成功上传。这是控制器动作

    [HttpPost]
    public string UploadFile(HttpPostedFileBase file)
    {
        if (file.ContentLength <= 0)
            throw new Exception("Error while uploading");

        string fileName = Path.GetFileName(file.FileName);
        string path = Path.Combine(Server.MapPath("~/Uploaded Files"), fileName);
        file.SaveAs(path);
        return "Successfuly uploaded";
    }


和视图的上传表单

@using (Html.BeginForm("UploadFile", "Documents", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.TextBox("file", "", new { type = "file" })
    <input type="submit" value="Dodaj fajl" />
}  

在该视图中,我有另一个名为DocumentNumber 的变量,我需要将其传递给UploadFile 操作。我只是猜想我的动作的标题应该是这样的:public string UploadFile(HttpPostedFileBase file, int docNo) 如果我想传递那个变量,但我也不知道如何在视图的表单中设置这个值。我尝试添加:new { enctype = "multipart/form-data", docNo = DocumentNumber } 没有成功。如何使用 post 方法将 DocumentNumber(需要隐藏,不可见)从我的视图传递到控制器的操作?

【问题讨论】:

    标签: c# asp.net-mvc post webforms


    【解决方案1】:

    为您的操作方法添加一个参数

    [HttpPost]
    public string UploadFile(HttpPostedFileBase file,int DocumentNumber)
    {
    
    }
    

    并确保您的表单具有相同名称的输入元素。它可以是隐藏的或可见的。当您提交表单时,输入值将与输入元素名称相同的名称发送,这与我们的操作方法参数名称匹配,因此值将映射到该名称。

    @using (Html.BeginForm("UploadFile", "Documents", FormMethod.Post,
                                         new { enctype = "multipart/form-data" }))
    {
        @Html.TextBox("file", "", new { type = "file" })
        <input type="text" name="DocumentNumber" value="123"/ >
        <input type="submit" value="Dodaj fajl" />
    }  
    

    如果您想使用模型的 DocumentNumber 属性值,您可以简单地使用其中一种辅助方法来生成具有该值的输入元素(您应该在 GET 操作方法中设置该值)

    @Html.TextBoxFor(s=>s.DocumentNumber)
    

    或者对于隐藏的输入元素

    @Html.HiddenFor(s=>s.DocumentNumber)
    

    【讨论】:

      猜你喜欢
      • 2014-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-28
      • 2012-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多