Hi nedash,
You can implement in the below way. In the ex variable you can able to see the error details.
Controller
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
return View();
}
public ActionResult Register(Customer customer)
{
CustomerRepository bl = new CustomerRepository();
if (ModelState.IsValid)
{
if (bl.Add(customer))
{
TempData["Message"] = "ثبت شد";
TempData["Style"] = "lightgreen";
}
else
{
TempData["Message"] = "ثبت نشد";
TempData["Style"] = "palevioletred";
}
}
else
{
TempData["Message"] = "مقادیر را بدرستی وارد کنید";
TempData["Style"] = "palevioletred";
}
return View("Index");
}
}
Repository Class
public class CustomerRepository
{
TestEntities db = new TestEntities();
public bool Add(Customer customer)
{
bool saved = false;
try
{
db.Customers.AddObject(customer);
saved = Convert.ToBoolean(db.SaveChanges());
}
catch (Exception ex)
{
}
return saved;
}
}
View
<body>
<div>
<%using (Html.BeginForm("Register", "Home", FormMethod.Post))
{%>
<table>
<tr>
<td>Name</td>
<td><%:Html.TextBoxFor(m=>m.Name) %></td>
</tr>
<tr>
<td>Country</td>
<td><%:Html.TextBoxFor(m=>m.Country) %></td>
</tr>
<tr>
<td><input type="submit" value="Register" /></td>
</tr>
</table>
<br />
<%} %>
<%if (TempData["Message"] != null)
{%>
<%=TempData["Message"] %>
<%} %>
</div>
</body>
Screenshot