Hi nabilabolo,
Check this example. Now please take its reference and correct your code.
SQL
CREATE TABLE WorkDetails
(
Id INT IDENTITY PRIMARY KEY,
WorkWeek INT,
DDPM INT
)
Model
public class WorkModel
{
[Required]
public int WorkWeek { get; set; }
[Required]
public int DPPM { get; set; }
}
Controller
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
TestEntities entities = new TestEntities();
TempData["Details"] = entities.WorkDetails.ToList();
return View(new WorkModel());
}
[HttpPost]
public ActionResult Index(WorkModel work)
{
if (ModelState.IsValid)
{
TestEntities entities = new TestEntities();
WorkDetail workDetail = entities.WorkDetails.Where(x => x.WorkWeek == work.WorkWeek).FirstOrDefault();
if (workDetail == null)
{
// Insert new record.
workDetail = new WorkDetail();
workDetail.WorkWeek = work.WorkWeek;
workDetail.DDPM = work.DPPM;
entities.WorkDetails.AddObject(workDetail);
entities.SaveChanges();
}
else
{
// Update record based on WorkWeek.
workDetail.DDPM = workDetail.DDPM + work.DPPM;
entities.SaveChanges();
}
return RedirectToAction("Index");
}
return View(work);
}
}
View
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<Insert_Update_MVC.Models.WorkModel>" %>
<%@ Import Namespace="Insert_Update_MVC" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Index</title>
</head>
<body>
<% using (Html.BeginForm()) {%>
<table>
<tr>
<td>
<%: Html.LabelFor(model => model.WorkWeek) %>
</td>
<td>
<%: Html.TextBoxFor(model => model.WorkWeek) %>
<%: Html.ValidationMessageFor(model => model.WorkWeek) %>
</td>
</tr>
<tr>
<td>
<%: Html.LabelFor(model => model.DPPM) %>
</td>
<td>
<%: Html.TextBoxFor(model => model.DPPM) %>
<%: Html.ValidationMessageFor(model => model.DPPM) %>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Save" />
</td>
</tr>
</table>
<% } %>
<hr />
<%if (TempData["Details"] != null) { %>
<table>
<tr>
<th>No.</th>
<th>Work Week</th>
<th>DPPM</th>
</tr>
<%foreach (WorkDetail wd in (List<WorkDetail>)TempData["Details"])
{%>
<tr>
<td><%= wd.Id%></td>
<td><%= wd.WorkWeek%></td>
<td><%= wd.DDPM%></td>
</tr>
<% } %>
</table>
<%} %>
</body>
</html>
Screenshot