Ajaxform plugin Best choice: jquery Forms plugin.
Here's an example:
Ajax.beginform
@using (Ajax.beginform ("youraction","Yourcontroller",NewAjaxoptions () {HttpMethod ="POST"},New{enctype ="Multipart/form-data"}) {@Html. AntiForgeryToken ()<input type="file"id=" file "Name="Files"><br> <input type="Submit"Value="Upload File to Server">}
Or
@using (Html.BeginForm ("youraction","Yourcontroller",New{area ="Yourarea"}, FormMethod.Post,New{enctype ="Multipart/form-data"}) {@Html. AntiForgeryToken ()<input type="file"id=" file "Name="Files"><br> <input type="Submit"Value="Upload File to Server">}
Action Method
[HttpPost] [Validateantiforgerytoken] Public voidYouraction (ienumerablefiles) { if(Files! =NULL) { foreach(varFileinchfiles) { //Verify that the user selected a file if(File! =NULL&& file. ContentLength >0) { //extract only the Fielname varFileName =path.getfilename (file. FileName); //todo:need to define destination varPath = Path.Combine (Server.MapPath ("~/upload"), fileName); File. SaveAs (path); } } } }
Need to note:
1,) If the current view page is not a ~{/area}/views/your/your.cshtml page, you can only return void,string, not viewresult,jsonresult,contentresult, etc.
1.1,) If you need to return a parameter, you can change the void to string.
1.2,) If you want to return an object, serialize the object to a string, return the string, and specify the return data format when the client commits: $ ("#file") Ajaxfrom ({data:{},datatype: ' json ',...}).
Progress Bar
<Divclass= "Progress progress-striped"> <Divclass= "Progress-bar progress-bar-success">0%</Div></Div><DivID= "status"></Div>
Jquery & Form Script
<Scriptsrc= "Http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></Script><Scriptsrc= "Http://malsup.github.com/jquery.form.js"></Script><Script>(function() {varBar= $('. Progress-bar');varpercent= $('. Progress-bar');varStatus= $('#status');$('form'). Ajaxform ({beforesend:function() {status.empty (); varPercentval= '0%'; Bar.width (Percentval) percent.html (percentval); }, Uploadprogress:function(event, Position, total, percentcomplete) {varPercentval=PercentComplete+ '%'; Bar.width (Percentval) percent.html (percentval); }, Success:function() { varPercentval= '100%'; Bar.width (Percentval) percent.html (percentval); }, Complete:function(XHR) {status.html (xhr.responsetext); }}); })(); </Script>
Reference: Http://stackoverflow.com/questions/19042116/ajax-beginform-in-mvc-to-upload-files
How to use Jquery/ajaxform to upload files in
ASP. NET MVC