除了一些简单的标量数据外,我还有几个文件需要保存。有没有办法让我验证文件是否已与其余表单数据一起发送?我正在尝试使用 [Required]
属性,但它似乎不起作用。
最佳答案
以下对我有用。
型号:
public class MyViewModel
{
[Required]
public HttpPostedFileBase File { get; set; }
}
Controller :
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var fileName = Path.GetFileName(model.File.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
model.File.SaveAs(path);
return RedirectToAction("Index");
}
}
查看:
<% using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { %>
<input type="file" name="file" />
<%= Html.ValidationMessageFor(x => x.File) %>
<input type="submit" value="OK" />
<% } %>
关于c# - 有没有办法验证 MVC 2 中传入的 HttpPostedFilebase 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6126472/