Learn to Upload a file in MVC via Ajax

1
16743
up

up

HI friends, today we are going to learn how to save a file in MVC.

File Upload in MVC
In asp.net, we use the control mentioned below to save a file to the server

But in MVC there are no asp.net controls, so basically we use normal control like below one and post it to the controller.

Which Means Loading a file in Asp.Net MVC application is very simple. The posted file is automatically available as HttpPostedFileBase parameters in the action of the control. To upload a file on the server we require a file input control in html form with enctype set to multipart/form-data.

So let’s start with the example. We are using Ajax post and get method in below example.

Open visual studio then click on file new project select asp.net MVC web application select Internet Application.
Java Programming Course for Beginner From Scratch
Now Open Index.cshtml inside ViewHome Folder and replace all the code in the folder with the code shown below.

1

Now open HomeController file, inside the Controllers folder and add the code below in it. Also create a UploadFile folder in the root directory.

2

Now run the application and see the output.

3

Summary: In above example we have learned how to post a file in MVC.

File Upload in MVC via ajax
Now if you want to save the file using Ajax, put the below code in index view. In this we have used Jquery Ajax request to save the file in server. Don’t forget to add Jquery lib reference.

Learn HTML5 Programming For Beginners
Now Open Home Controller and paste the code shown below.

Now run the application and see the result.
Summary: In above example we have learnt how to post a file in MVC via ajax post.

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here