Hi nedash,
Check this example. Now please take its reference and correct your code.
Namespaces
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
Model
public class User
{
[DisplayName("Id")]
public string UserId { get; set; }
[Required]
[DisplayName("Name")]
public string UserName { get; set; }
[Required]
[DisplayName("Country")]
public string Country { get; set; }
[DataType(DataType.DateTime), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
[DisplayName("Birthday")]
public DateTime? Birthday { get; set; }
}
Utility
public static class Utility
{
public static string GetErrors(this ModelStateDictionary modelState)
{
return string.Join("<br />", (from item in modelState
where item.Value.Errors.Any()
select item.Value.Errors[0].ErrorMessage).ToList());
}
}
Controller
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(User user)
{
if (ModelState.IsValid)
{
TempData["Success"] = "User Inserted Successfully.";
}
else
{
TempData["Error"] = Utility.GetErrors(ModelState);
}
return View("Index");
}
}
View
<body>
<div>
<%using (Html.BeginForm("Register", "Home", FormMethod.Post)) {%>
<%:Html.AntiForgeryToken() %>
<div class="form-horizontal">
<div class="text-center">
<div class="text-center">
<%:Html.HiddenFor(m => m.UserId)%>
<div class="form-group">
<div class="col-md-10">
<%:Html.LabelFor(model => model.UserId)%>
<%:Html.EditorFor(model => model.UserId, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })%>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<%:Html.LabelFor(model => model.UserName)%>
<%:Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })%>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<%:Html.LabelFor(model => model.Country)%>
<%:Html.EditorFor(model => model.Country, new { htmlAttributes = new { @class = "form-control" } })%>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<%:Html.LabelFor(model => model.Birthday)%>
<%:Html.EditorFor(model => model.Birthday, new { htmlAttributes = new { @class = "form-control" } })%>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input type="submit" value="Save" class="btn btn-success" />
</div>
</div>
<%if (TempData["Success"] != null) {%>
<span> <%=TempData["Success"] %></span>
<% } %>
<br />
<%if (TempData["Error"] != null) {%>
<span> <%=TempData["Error"]%></span>
<% } %>
</div>
</div>
</div>
<%} %>
</div>
</body>
Screenshot
