博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ASP.NET MVC上传文件
阅读量:4702 次
发布时间:2019-06-09

本文共 2257 字,大约阅读时间需要 7 分钟。

最近参考网络资料,学习了ASP.NET MVC如何上传文件。最基本的,没有用jQuery等技术。

1、定义Model

    public class TestModel

    {
        [Display(Name = "标题")]
        [Required]
        public string Title
        {
            get;
            set;
        }
        [Display(Name = "内容")]
        [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();        }        ///         /// 提交方法        ///         /// 模型数据        /// 上传的文件对象,此处的参数名称要与View中的上传标签名称相同        /// 
[HttpPost] public ActionResult Upload(TestModel tm, HttpPostedFileBase file) { if (file == null) { return Content("没有文件!", "text/plain"); } var fileName = Path.Combine(Request.MapPath("~/Upload"), Path.GetFileName(file.FileName)); try { file.SaveAs(fileName); //tm.AttachmentPath = fileName;//得到全部model信息 tm.AttachmentPath = "../upload/" + Path.GetFileName(file.FileName); //return Content("上传成功!", "text/plain"); return RedirectToAction("Show",tm); } catch { return Content("上传异常 !", "text/plain"); } } public ActionResult Show(TestModel tm) { return View(tm); } }

 3、View

3.1 Upload.cshtml

@model MvcApplication1.Models.TestModel@{    ViewBag.Title = "Upload";}    普通上传    @*enctype= "multipart/form-data"是必需有的,否则action接收不到相应的file*@    @using (Html.BeginForm("Upload", "Test", FormMethod.Post, new { enctype = "multipart/form-data" }))    {        @Html.LabelFor(mod => mod.Title)        
@Html.EditorFor(mod => mod.Title)
@Html.LabelFor(mod => mod.Content)
@Html.EditorFor(mod => mod.Content)
上传文件
}

 3.2 Show.cshtml

@model MvcApplication1.Models.TestModel@{    ViewBag.Title = "Show";}

Show

@Html.LabelFor(mod => mod.Title)
@Html.EditorFor(mod => mod.Title)
@Html.LabelFor(mod => mod.Content)
@Html.EditorFor(mod => Model.Content)
图片:img

 

转载于:https://www.cnblogs.com/zhouhb/p/3906714.html

你可能感兴趣的文章
一个强大的UI node 抽象
查看>>
MVC,MVP 和 MVVM 的图示
查看>>
openwrt opkg update wget returned 4 wget returned 1
查看>>
.net + Android 通信
查看>>
C#dataset中数据导出到excel
查看>>
node和yarn
查看>>
hdu 4325
查看>>
移动端 html基值(转载)
查看>>
开源框架 系统
查看>>
积木艺术 (Cubist Artwork,Tokyo 2009,LA 4636)
查看>>
lvs+keepalived实现高可用群集配置详解
查看>>
Java连接MySQL数据库——含详细步骤和代码
查看>>
[平面文件源 [1]] 错误: 数据转换失败。列“列 1”的数据转换返回状态值 4 和状态...
查看>>
漫谈二分查找-Binary Search (转)
查看>>
编写自定义类实现json和pickle文件的多行写入,多行读取
查看>>
如果一个网页需要同时有多种语言,那么网页需要用什么编码格式?
查看>>
fast-json 内幕
查看>>
固定导航栏demo
查看>>
前端通信、跨域
查看>>
MD5加密
查看>>