Mon*_*set 5 c# asp.net-mvc post webforms
我正在使用这个简单的教程在我的 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";
}
Run Code Online (Sandbox Code Playgroud)
和视图的上传表单
@using (Html.BeginForm("UploadFile", "Documents", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.TextBox("file", "", new { type = "file" })
<input type="submit" value="Dodaj fajl" />
}
Run Code Online (Sandbox Code Playgroud)
在那个视图中,我有另一个名为 的变量DocumentNumber,我需要将其传递给UploadFile操作。我只是猜测我的动作的标题看起来像这样:public string UploadFile(HttpPostedFileBase file, int docNo)如果我想传递那个变量,但我也不知道如何在视图的表单中设置这个值。我尝试添加:new { enctype = "multipart/form-data", docNo = DocumentNumber }没有成功。如何DocumentNumber使用 post 方法将(需要隐藏,不可见)从我的视图传递到控制器的操作?
将参数添加到您的操作方法
[HttpPost]
public string UploadFile(HttpPostedFileBase file,int DocumentNumber)
{
}
Run Code Online (Sandbox Code Playgroud)
并确保您的表单有一个同名的输入元素。它可以是隐藏的或可见的。当您提交表单时,输入值将以与输入元素名称相同的名称发送,该名称与我们的操作方法参数名称匹配,因此值将映射到该名称。
@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" />
}
Run Code Online (Sandbox Code Playgroud)
如果您想使用DocumentNumber模型的属性值,您可以简单地使用其中一种辅助方法来生成具有该值的输入元素(您应该在 GET 操作方法中设置)
@Html.TextBoxFor(s=>s.DocumentNumber)
Run Code Online (Sandbox Code Playgroud)
或者对于隐藏的输入元素
@Html.HiddenFor(s=>s.DocumentNumber)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8227 次 |
| 最近记录: |