ok, so firstly, take a look on this: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-validation-to-the-model
Secondly, I would recommend to use ViewModels to validate objects. Like in code below (in shortcut):
MemberViewModel.cs
public class MemberViewModel
{
[Required]
[StringLength(10)]
public string mName { get; set; }
[Required]
public string mLName { get; set; }
}
And then, send your ViewModel to Edit/Add view:
Add.cshtml
@Model MemberViewModel //namespace etc.
@using (Html.BeginForm("Add"))
{
@Html.ValidationSummary()
@ViewBag.Status
@Html.LabelFor(m => m.mName)
@Html.TextBoxFor(m => m.mName)
@Html.ValidationMessageFor(m => m.mName)
@Html.LabelFor(m => m.mLName)
@Html.TextBoxFor(m => m.mLName)
@Html.ValidationMessageFor(m => m.mLName)
<input type="submit" />
}
Controler and Add ActionResult
[HttpPost]
public ActionResult Add(MemberViewModel model)
{
if (ModelState.IsValid)
{
Member memberToAdd = new Member{ };
memberToAdd.mLName = model.mLName;
memberToAdd.mName = model.mName;
(..)
//some operation, perhaps on database, with memberToAdd
return RedirectToAction("xyz");
}
else
return View(model);
}
With this approach, you have clear Entity model (POCO
classes like Member
) and Domian models (ViewModels
like MemberViewModel) with custom validation.