ASP.NET MVC Prześlij obraz
[HttpGet]
public ActionResult Add_Category()
{
return View();
}
[HttpPost]
public ActionResult Add_Category(tbl_category cat , HttpPostedFileBase file)
{
string path = uploadimage(file);
if (path.Equals("-1"))
{
ViewBag.error = "Image could not be uploaded";
}
else
{
tbl_category ca = new tbl_category();
ca.cat_name = cat.cat_name;
ca.cat_status = cat.cat_status;
ca.cat_image = path;
ca.ad_id_fk = Convert.ToInt32(Session["ad_id"].ToString());
db.tbl_category.Add(ca);
db.SaveChanges();
return RedirectToAction("ViewCategory");
}
return View();
//upload image
public string uploadimage(HttpPostedFileBase file)
{
Random r = new Random();
string path = "-1";
int random = r.Next();
if (file != null && file.ContentLength > 0)
{
string extension = Path.GetExtension(file.FileName);
if (extension.ToLower().Equals(".jpg") || extension.ToLower().Equals(".jpeg") || extension.ToLower().Equals(".png"))
{
try
{
path = Path.Combine(Server.MapPath("~/Content/upload/"), random + Path.GetFileName(file.FileName));
file.SaveAs(path);
path = "~/Content/upload/" + random + Path.GetFileName(file.FileName);
}
catch (Exception ex)
{
path = "-1";
}
}
else
{
Response.Write("<script>alert('ONLY JPG,JPEG AND PNG Formats are Acceptable'); </script>");
}
}
else
{
Response.Write("<script>alert('Please Select a File'); </script>");
path = "-1";
}
return path;
Cruel Crab