Hi sani.ss501,
Refer below sample.
Database
CREATE TABLE tbl_category
(
id int PRIMARY KEY IDENTITY,
title nvarchar(50),
PId int,
Image nvarchar(max)
)
INSERT INTO tbl_category VALUES('soft',0,'upload/1.png')
INSERT INTO tbl_category VALUES('network',0,'upload/2.png')
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
tbl_category cat = new tbl_category();
CategoryEntities entity = new CategoryEntities();
ViewBag.Category = entity.tbl_category.Where(x => x.PId == 0).Select(x => new SelectListItem { Text = x.id.ToString(), Value = x.id.ToString() });
return View(cat);
}
public ActionResult Upload(tbl_category cat)
{
HttpPostedFileBase postedFile = Request.Files["postedFile"];
string path = Server.MapPath("~/upload/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
postedFile.SaveAs(path + Path.GetFileName(postedFile.FileName));
cat.Image = "upload/" + Path.GetFileName(postedFile.FileName);
CategoryEntities entity = new CategoryEntities();
tbl_category isExist = entity.tbl_category.Where(x => x.title == cat.title).FirstOrDefault();
if (isExist != null)
{
isExist.PId = cat.PId;
isExist.Image = cat.Image;
}
else
{
entity.tbl_category.Add(cat);
}
entity.SaveChanges();
return RedirectToAction("Index");
}
}
View
@model Insert_Parent_MVC.tbl_category
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr>
<td>Title</td>
<td>@Html.TextBoxFor(m => m.title)</td>
</tr>
<tr>
<td>Id</td>
<td>@Html.DropDownListFor(m => m.PId, new SelectList(ViewBag.Category, "Text", "Value"), "Please select", new { @id = "ddlCategories" })</td>
</tr>
<tr>
<td>Select File</td>
<td><input type="file" name="postedFile" /></td>
</tr>
</table> <hr />
<input type="submit" value="Upload" />
}
</body>
</html>