我正在尝试在MVC中实现文件上传。我有以下代码可行。
@using (Html.BeginForm("ActioName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
<input type="file" name="file" />
<input type="submit" value="OK" class="button" />
</div>
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
//do something here...
}
}
现在我想添加一个下拉框(选择文件类型)并将该值与文件一起发送到Controller。我该怎么做(将其他表单数据与文件一起发送)?
答案 0 :(得分:10)
您应该能够将它们添加到视图中,将它们包含在POST中并让MVC处理模型绑定:
@using (Html.BeginForm("ActioName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
<input type="file" name="file" />
<select name="fileType">
<option value="JPG">Photo</option>
<option value="DOC">Word</option>
</select>
<input type="submit" value="OK" class="button" />
</div>
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file, string fileType)
{
//Validate the fileType
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
//do something here...
}
}
答案 1 :(得分:3)
我最终按如下方式进行操作。对我有用:
创建了一个模型:
public class FeeUpload
{
[Required (ErrorMessage="File Type required")]
public string fileType { get; set; }
[Required (ErrorMessage="file required")]
public HttpPostedFileBase File { get; set; }
}
查看:
@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(false, "Please fix the following:")
<div>
<div>
@Html.DropDownListFor(model => model.fileType,
new List<SelectListItem>
{
new SelectListItem{ Text="xxx", Value = "yyy" },
new SelectListItem{ Text="xxx", Value = "yyy" },
new SelectListItem{ Text="xxx", Value = "yyy" }
}, "Select")
@*@Html.ValidationMessageFor(model => model.fileType)*@
</div>
<div>
@Html.TextBoxFor(model => model.File, new { type = "file" })
@*@Html.ValidationMessageFor(model => model.File)*@
<input type="submit" value="OK" class="button" id="btnsubmit" />
</div>
</div>
}
控制器:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FeesAndCostsUpload(FeeUpload feeUploadFile)
{
if (ModelState.IsValid)
{
//do something with feeUploadFile.File and feeUploadFile.fileType
}
return View();
}
答案 2 :(得分:0)
尽量不要将Razor用于表格
<form method="POST" data-url="@Url.Action("Action", "Controller")" enctype="multipart/form-data">
@Html.ValidationSummary(true)
<span class="btn btn-success fileinput-button">
<i class="fa fa-plus"></i>
<span>Add a file...</span>
@Html.TextBoxFor(model => model.Fichier, new { type = "file" })
</span>
<div class="form-group form-actions">
<div class="col-sm-offset-3 col-sm-9">
<input id="submit" type="submit" class="btn btn-primary" value='Value' />
</div>
</div>
</form>
为我工作