Sunday 24 September 2017

Fileupload validation using Model Data Annotations in ASP.Net MVC

Fileupload validation using Model Data Annotations in ASP.Net MVC


Description:

In this example we explain that how to validate FileUpload in asp.Net MVC using Data Annotations MVC.or how to validate File Upload using Data Annotations in MVC.here we validate fileuplaod only allow Image File with using regular expression in MVC Data Annotations.

Here we demonstrate that Upload File using Model Validation in MVC.or how to validate file type of HttpPostedFileBase attribute in MVC using Data Annotations.
Model:

public class FileModel
    {
        [Required(ErrorMessage = "Please select file.")]
        [RegularExpression(@"([a-zA-Z0-9\s_\\.\-:])+(.png|.jpg|.gif)$", ErrorMessage = "Only Image files allowed.")]
        public HttpPostedFileBase PostedFile { get; set; }
    }
public class EmployeeController : Controller
    {

Controller:

[HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(HttpPostedFileBase postedFile)
        {
            string path = Server.MapPath("~/Uploads/");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            if (postedFile != null)
            {
                string fileName = Path.GetFileName(postedFile.FileName);
                postedFile.SaveAs(path + fileName);
                ViewBag.Message += string.Format("<b>{0}</b> uploaded.<br />", fileName);
            }

            return View();
        }

}

View:

@model FileUpload_Validation_MVC.Models.FileModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Fileupload validation using Model Data Annotations in ASP.Net MVC</title>
</head>
<body>
    <div>
        @using (Html.BeginForm("Index", "Employee", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
            <span>Select File:</span>
            @Html.TextBoxFor(m => m.PostedFile, new { type = "file"})
            <br/>
            @Html.ValidationMessageFor(m => m.PostedFile, "", new { @class = "error" })
            <hr/>
            <input type="submit" value="Upload"/>
            <br/>
            <span style="color:green">@Html.Raw(ViewBag.Message)</span>
        }
    </div>
</body>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
</html>


This entry was posted in :

0 comments:

Post a Comment