Is there a way to validate incoming HttpPostedFilebase files in MVC 2?

后端 未结 1 1379
猫巷女王i
猫巷女王i 2020-12-18 16:43

I have a couple of files I need to save in addition to some simple scalar data. Is there a way for me to validate that the files have been sent along with the rest of the f

相关标签:
1条回答
  • 2020-12-18 17:17

    The following worked for me.

    Model:

    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");
        }
    }
    

    View:

    <% 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" />
    <% } %>
    
    0 讨论(0)
提交回复
热议问题