首页 > 代码库 > 扩展属性的使用

扩展属性的使用

今天在写MVC项目代码的时候,遇到一个上传的问题,其中要判断是否选择了上传文件就想着用扩展属性实现,因为很久没用了顺便回顾一下,但是写完以后始终不能调用,最后上网查了查,扩展属性所在的类必须是静态类

扩展属性静态类:

 public static class ExtendMethodForHttpPostedFileBaseClass
    {
        public static bool HasFile(this HttpPostedFileBase control)
        {
            return control != null && control.ContentLength > 0;
        }
    }
}

调用:

[HttpPost]
        public ActionResult Index(string up)
        {
            HttpFileCollectionBase files = Request.Files;
            foreach (string filen in files)
            {
                HttpPostedFileBase fileUploadCon = files[filen];
                if (fileUploadCon.HasFile())
                {
                    string path = Server.MapPath("~/upload/");
                    fileUploadCon.SaveAs(path + (fileUploadCon.FileName.IndexOf(‘\\‘) != -1 ? fileUploadCon.FileName.Substring(fileUploadCon.FileName.LastIndexOf(‘\\‘) + 1) : fileUploadCon.FileName));
                }
            }
            Response.Write("<script>alert(\"上传成功!\");</script>");
            return View(Index());
        }