0% found this document useful (0 votes)
17 views

File Upload With Strongly Typed View and Model Validation

This document discusses how to upload files in ASP.NET MVC using a strongly typed view and model validation. It covers designing a model with validation attributes, creating a view based on the model, adding jQuery validation, and handling file upload in the controller. The approach allows validating files on both the client-side and server-side.

Uploaded by

Raghu Gowda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

File Upload With Strongly Typed View and Model Validation

This document discusses how to upload files in ASP.NET MVC using a strongly typed view and model validation. It covers designing a model with validation attributes, creating a view based on the model, adding jQuery validation, and handling file upload in the controller. The approach allows validating files on both the client-side and server-side.

Uploaded by

Raghu Gowda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

6/27/2014 File upload with strongly typed view and model validation

File upload with strongly typed view and model


validation
P o st e d By : S h aile ndra Ch auh an, 0 9 Jan 2 0 1 3
U pdat e d On : 1 1 Jun 2 0 1 4
V e rs i o n Su p p o rt : MV C4 & MV C3

Ke y wo rd s : v a l i d a t e fi l e u s i n g d a t a a n n o t a t i o n ,u p l o a d fi l e i n mv c4 i n s t ro n g l y t y p e d v i e w,fi l e
v a l i d a t i o n u s i n g jq u e ry i n mv c3 mv c4 i n s t ro n g l y t y p e d v i e w

M any times, we required to upload file with strongly-typed view and also apply validation on uploading file using
data annotation validators. In this article, I would like to share, how can we upload a file and validate that file,
firstly at client side and after that at server side.

How to do it..
Step 1 : Designing model with data annotation validation

1. public class RegistrationModel


2. {
3. [Required(ErrorMessage = "Please Enter Your Full Name")]
4. [Display(Name = "Full Name")]
5. public string Name { get; set; }
6.
7. [Required(ErrorMessage = "Please Enter Address")]
8. [Display(Name = "Address")]
9. [MaxLength(200)]
10. public string Address { get; set; }
11.
12. [Required(ErrorMessage = "Please Upload File")]
13. [Display(Name = "Upload File")]
14. [ValidateFile]
15. public HttpPostedFileBase file { get; set; }
16. }
17.
18. //Customized data annotation validator for uploading file
19. public class ValidateFileAttribute : ValidationAttribute
20. {
21. public override bool IsValid(object value)
22. {
23. int MaxContentLength = 1024 * 1024 * 3; //3 MB
24. string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
25.
26. var file = value as HttpPostedFileBase;
27.
28. if (file == null)
29. return false;
30. else if

http://www.dotnet-tricks.com/Tutorial/mvc/aX9D090113-File-upload-with-strongly-typed-view-and-model-validation.html 1/6
6/27/2014 File upload with strongly typed view and model validation

(!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
31. {
32. ErrorMessage = "Please upload Your Photo of type: " + string.Join(", ",
AllowedFileExtensions);
33. return false;
34. }
35. else if (file.ContentLength > MaxContentLength)
36. {
37. ErrorMessage = "Your Photo is too large, maximum allowed size is : " + (MaxContentLength
/ 1024).ToString() + "MB";
38. return false;
39. }
40. else
41. return true;
42. }
43. }

Step 2 : Designing view based on model

1. <h2>File upload with model validation</h2>


2. <h3 style="color: green">@ViewBag.Message</h3>
3.
4. @using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype =
"multipart/form-data" }))
5. {
6. <fieldset>
7. <legend></legend>
8. <ol>
9. <li>
10. @Html.LabelFor(m => m.Name)
11. @Html.TextBoxFor(m => m.Name, new { maxlength = 50 })
12. @Html.ValidationMessageFor(m => m.Name)
13. </li>
14. <li>
15. @Html.LabelFor(m => m.Address)
16. @Html.TextAreaFor(m => m.Address, new { maxlength = 200 })
17. @Html.ValidationMessageFor(m => m.Address)
18. </li>
19. <li class="lifile">
20. @Html.TextBoxFor(m => m.file, new { type = "file" })
21. @Html.ValidationMessageFor(m => m.file)
22. </li>
23. </ol>
24. <input type="submit" value="Submit" />
25. </fieldset>
26. }

http://www.dotnet-tricks.com/Tutorial/mvc/aX9D090113-File-upload-with-strongly-typed-view-and-model-validation.html 2/6
6/27/2014 File upload with strongly typed view and model validation

Step 3 : Applying jQuery validation for validating file

1. <script type="text/jscript">
2. //get file size
3. function GetFileSize(fileid) {
4. try {
5. var fileSize = 0;
6. //for IE
7. if ($.browser.msie) {
8. //before making an object of ActiveXObject,
9. //please make sure ActiveX is enabled in your IE browser
10. var objFSO = new ActiveXObject("Scripting.FileSystemObject"); var filePath = $("#" +
fileid)[0].value;
11. var objFile = objFSO.getFile(filePath);
12. var fileSize = objFile.size; //size in kb
13. fileSize = fileSize / 1048576; //size in mb
14. }
15. //for FF, Safari, Opeara and Others
16. else {
17. fileSize = $("#" + fileid)[0].files[0].size //size in kb
18. fileSize = fileSize / 1048576; //size in mb
19. }
20.
21. return fileSize;
22. }
23. catch (e) {
24. alert("Error is :" + e);
25. }
26. }
27.
28. //get file path from client system
29. function getNameFromPath(strFilepath) {
30. var objRE = new RegExp(/([^\/\\]+)$/);
31. var strName = objRE.exec(strFilepath);
32.
33. if (strName == null) {
34. return null;
35. }
36. else {
37. return strName[0];
38. }
39. }
40.
41. $(function () {
42. $("#file").change(function () {
43. var file = getNameFromPath($(this).val());

http://www.dotnet-tricks.com/Tutorial/mvc/aX9D090113-File-upload-with-strongly-typed-view-and-model-validation.html 3/6
6/27/2014 File upload with strongly typed view and model validation

44. if (file != null) {


45. var extension = file.substr((file.lastIndexOf('.') + 1));
46. switch (extension) {
47. case 'jpg':
48. case 'png':
49. case 'gif':
50. case 'pdf':
51. flag = true;
52. break;
53. default:
54. flag = false;
55. }
56. }
57. if (flag == false) {
58. $(".lifile > span").text("You can upload only jpg,png,gif,pdf extension file");
59. return false;
60. }
61. else {
62. var size = GetFileSize('file');
63. if (size > 3) {
64. $(".lifile > span").text("You can upload file up to 3 MB");
65. }
66. else {
67. $(".lifile > span").text("");
68. }
69. }
70. });
71. });
72. </script>

Step 4 : Designing Controller

1. public ActionResult FileUpload()


2. {
3. return View();
4. }
5.
6. [HttpPost]
7. public ActionResult FileUpload(RegistrationModel mRegister)
8. {
9. //Check server side validation using data annotation
10. if (ModelState.IsValid)
11. {
12. //TO:DO
13. var fileName = Path.GetFileName(mRegister.file.FileName);
14. var path = Path.Combine(Server.MapPath("~/Content/Upload"), fileName);

http://www.dotnet-tricks.com/Tutorial/mvc/aX9D090113-File-upload-with-strongly-typed-view-and-model-validation.html 4/6
6/27/2014 File upload with strongly typed view and model validation

15. mRegister.file.SaveAs(path);
16. ViewBag.Message = "File has been uploaded successfully";
17. ModelState.Clear();
18. }
19. return View();
20. }

How it works...

What do you think?


I hope you will enjoy the tips while working with MVC. I would like to have feedback from my blog readers. Your valuable
feedback, question, or comments about this article are always welcome.
Download Code

http://www.dotnet-tricks.com/Tutorial/mvc/aX9D090113-File-upload-with-strongly-typed-view-and-model-validation.html 5/6
6/27/2014 File upload with strongly typed view and model validation

Print Article

Share this article with your friends!


in S h a r e 1

Tw eet

About the Author

Shailendra Chauhan works as Software Analyst at reputed MNC and has more than 5 years of hand over Microsoft
.NET technologies. He is a .NET Consultant and is the founder & chief editor of www.dotnet-tricks.com and
www.dotnetinterviewtricks.com blogs. He is an author of book ASP.NET MVC Interview Questions and Answers.
He loves to work with web applications and mobile apps using Microsoft technology including ASP.NET, MVC, C#,
SQL Server, WCF, Web API, Entity Framework,Cloud Computing, Windows Azure, jQuery, jQuery Mobile, Knockout.js,
Angular.js and many more web technologies. More...

http://www.dotnet-tricks.com/Tutorial/mvc/aX9D090113-File-upload-with-strongly-typed-view-and-model-validation.html 6/6

You might also like