博客
关于我
强烈建议你试试无所不能的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

你可能感兴趣的文章
BZOJ2213 : [Poi2011]Difference
查看>>
聊聊javascript的事件
查看>>
对象基础
查看>>
【MySQL比知必会】第九章 使用正则表达式进行搜索
查看>>
查看Oracle数据库名和实例名的命令
查看>>
20155302 2016-2017-2 《Java程序设计》第4周总结
查看>>
java Html 转 PDF
查看>>
C++ 标准库 permutation
查看>>
关于PCB开窗
查看>>
【蓝桥杯单片机07】彻底理解51单片机的中断系统
查看>>
款待奶牛
查看>>
APIO 2018选圆圈
查看>>
RabbitMQ,Redis
查看>>
C语言 可变参数的用法
查看>>
数据结构(树套树):ZJOI 2013 K大数查询
查看>>
ruby on rails安装(win7x64)
查看>>
kotlin成长之路
查看>>
建造者模式
查看>>
hdu1114-Piggy-Bank
查看>>
Ionic开发-如何在ion-content形成上下结构 上面固定下层可滚动
查看>>