Recently, I've learned how ASP. NET MVC uploads files by referencing network data. Most basic, not with jquery and other technologies.
1. Define Model
public class Testmodel
{
[Display (Name = "title")]
[Required]
public string Title
{
Get
Set
}
[Display (Name = "content")]
[Required]
[DataType (Datatype.multilinetext)]
public string Content
{
Get
Set
}
public string AttachmentPath
{
Get
Set
}
}
2. Controller
public class Testcontroller:controller {////GET:/test/public actionresult Upload () {return View (); }///<summary>/////</summary>//<param Name= "TM" > Model data </param& Gt <param name= "File" > uploaded object with the same parameter name as the upload tag name in view </param>//<returns></returns> [HttpPost] public actionresult Upload (Testmodel TM, HttpPostedFileBase file) {if (file = = nul L) {return Content ("No Files! "," Text/plain "); } var fileName = Path.Combine (Request.mappath ("~/upload"), Path.getfilename (file. FileName)); try {file. SaveAs (FileName); Tm. AttachmentPath = filename;//Get all the Model information TM. AttachmentPath = ". /upload/"+ path.getfilename (file. FileName); return Content ("Upload successful! "," Text/plain ");Return redirecttoaction ("Show", TM); } catch {return Content ("Upload exception! "," Text/plain "); }} public ActionResult Show (Testmodel tm) {return View (tm); } }
3. View
3.1 upload.cshtml
@model mvcapplication1.models.testmodel@{ viewbag.title = "Upload";} <! DOCTYPE html>
3.2 show.cshtml
@model mvcapplication1.models.testmodel@{ viewbag.title = "Show";}