public
class
BlogController : Controller
{
BlogContainer blogContainer =
new
BlogContainer();
public
ActionResult Index()
{
return
View(blogContainer.Blogs);
}
public
ActionResult Details(
int
id)
{
var
blog = blogContainer.Blogs.SingleOrDefault(b => b.Id == id);
return
View(blog);
}
public
ActionResult Create()
{
return
View();
}
[HttpPost]
[ValidateInput(
false
)]
public
ActionResult Create(Blog blog)
{
try
{
if
(ModelState.IsValid)
{
blogContainer.AddToBlogs(blog);
blogContainer.SaveChanges();
}
return
RedirectToAction(
"Index"
);
}
catch
{
return
View();
}
}
public
ActionResult Edit(
int
id)
{
var
blog = blogContainer.Blogs.SingleOrDefault(b => b.Id == id);
return
View(blog);
}
[HttpPost]
[ValidateInput(
false
)]
public
ActionResult Edit(
int
id, FormCollection collection)
{
try
{
if
(ModelState.IsValid)
{
var
blog = blogContainer.Blogs.SingleOrDefault(b => b.Id == id);
UpdateModel(blog, collection);
blogContainer.SaveChanges();
return
RedirectToAction(
"Index"
);
}
else
{
return
View();
}
}
catch
{
return
View();
}
}
public
ActionResult Delete(
int
id)
{
var
blog = blogContainer.Blogs.SingleOrDefault(b => b.Id == id);
blogContainer.Blogs.DeleteObject(blog);
blogContainer.SaveChanges();
return
RedirectToAction(
"Index"
);
}
[HttpPost]
public
ActionResult Delete(
int
id, FormCollection collection)
{
try
{
return
RedirectToAction(
"Index"
);
}
catch
{
return
View();
}
}
[HttpPost]
public
ActionResult UploadImage()
{
string
savePath =
"../Content/Images/"
;
string
fileTypes =
"gif,jpg,jpeg,png,bmp"
;
int
maxSize = 1000000;
Hashtable hash =
new
Hashtable();
HttpPostedFileBase file = Request.Files[
"imgFile"
];
if
(file ==
null
)
{
hash =
new
Hashtable();
hash[
"error"
] = 0;
hash[
"url"
] =
"请选择文件"
;
return
Json(hash);
}
string
dirPath = Server.MapPath(savePath);
if
(!Directory.Exists(dirPath))
{
hash =
new
Hashtable();
hash[
"error"
] = 0;
hash[
"url"
] =
"上传目录不存在"
;
return
Json(hash);
}
string
fileName = file.FileName;
string
fileExt = Path.GetExtension(fileName).ToLower();
ArrayList fileTypeList = ArrayList.Adapter(fileTypes.Split(
','
));
if
(file.InputStream ==
null
|| file.InputStream.Length > maxSize)
{
hash =
new
Hashtable();
hash[
"error"
] = 0;
hash[
"url"
] =
"上传文件大小超过限制"
;
return
Json(hash);
}
if
(
string
.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(
','
), fileExt.Substring(1).ToLower()) == -1)
{
hash =
new
Hashtable();
hash[
"error"
] = 0;
hash[
"url"
] =
"上传文件扩展名是不允许的扩展名"
;
return
Json(hash);
}
string
newFileName = DateTime.Now.ToString(
"yyyyMMddHHmmss_ffff"
, DateTimeFormatInfo.InvariantInfo) + fileExt;
string
filePath = dirPath + newFileName;
file.SaveAs(filePath);
string
fileUrl = saveUrl + newFileName;
hash =
new
Hashtable();
hash[
"error"
] = 0;
hash[
"url"
] = fileUrl;
return
Json(hash,
"text/html;charset=UTF-8"
);;
}
}
请发表评论