1. The Model layer uses a TestModel
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 layer:
Public class TestController: Controller
{
Public ActionResult View1 ()
{
Return View ();
}
/// <Summary>
/// Submission method
/// </Summary>
/// <Param name = "tm"> model data </param>
/// <Param name = "file"> the object to be uploaded. The parameter name here must be the same as the upload tag name in View. </param>
/// <Returns> </returns>
[HttpPost]
Public ActionResult View1 (TestModel tm, HttpPostedFileBase file)
{
If (file = null)
{
Return Content ("no file! "," Text/plain ");
}
Var fileName = Path. Combine (Request. MapPath ("~ /UploadFiles "), Path. GetFileName (file. FileName ));
Try
{
File. SaveAs (fileName );
Tm. AttachmentPath = fileName; // obtain all model information.
Return Content ("uploaded successfully! "," Text/plain ");
}
Catch
{
Return Content ("Upload exception! "," Text/plain ");
}
}
}
3. View layer:
@ Model UploadFile. Models. TestModel
@{
Layout = null;
}
<! DOCTYPE html>
<Html>
<Head>
<Meta name = "viewport" content = "width = device-width"/>
<Title> normal upload </title>
</Head>
<Body>
@ * Enctype = "multipart/form-data" is required; otherwise, the action cannot receive the corresponding file *@
@ Using (Html. BeginForm ("View1", "Test", FormMethod. Post, new {enctype = "multipart/form-data "}))
{
@ Html. LabelFor (mod => mod. Title)
<Br/>
@ Html. EditorFor (mod => mod. Title)
<Br/>
@ Html. LabelFor (mod => mod. Content)
<Br/>
@ Html. EditorFor (mod => mod. Content)
<Br/>
<Span> upload a file </span>
<Br/>
<Input type = "file" name = "file"/>
<Br/>
<Br/>
<Input id = "ButtonUpload" type = "submit" value = "submit"/>
}
</Body>
</Html>
<Input id = "ButtonUpload" type = "submit" value = "submit"/>
}
</Body>
</Html>
This page uploads files and submits data at the same time. In the action, first save the file on the server side, and then assign the server path to the AttachmentPath attribute in TestModel so that it can be stored in the background ......