MVC 5使用一个附加参数上传文件(POST)
问题描述:
我使用this简单教程在我的MVC5 C#VS2015项目中上传文件,并且无需控制器中的其他参数操作,即可成功上载文件。下面是控制器动作MVC 5使用一个附加参数上传文件(POST)
[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 }
没有成功。我如何通过DocumentNumber
(需要隐藏,不可见)从我的视角到控制器的后置方法?
答
参数添加到您的操作方法
[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)