ASP. NET MVC upload file

Source: Internet
Author: User
Tags tag name

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";} 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.