I am inserting Full Name in table using Entity Framework.
Before inserting I want to check if the record is already inserted.
Here is my View model,model and
You can add a new error to ModelStateDictionary if the user exist in the db.
Also, Looks like your view is only sending FullName and LastName. In that case, why not keep your view model to have only those properties so that your view specific-view model will not have any tight coupling with your entity models.
public class CreateUserVM
{
[Required]
public string FullName { set;get;}
public string LastName { set;get;}
}
And in your GET action make sure you are sending an object of this
public ActionResult Create()
{
return View(new CreateUserVM());
}
and your view will be strongly typed to our flat view model
@model CreateUserVM
@using(Html.BeginForm())
{
@Html.ValidationSummary(false)
@Html.TextBoxFor(s=>s.FullName)
@Html.TextBoxFor(s=>s.LastName)
}
and your HttpPost action method will be
public ActionResult Create(CreateUserVM model)
{
if (ModelState.IsValid)
{
var exist= db.Users.Any(x => x.FullName == model.FullName)
if(exist)
{
ModelState.AddModelError(string.Empty, "Username exists");
return View(vmModel);
}
var user = new Users()
{
FullName = model.FullName,
LastName = model.LastName
};
//Inserting in Parent table to get the Id that we will used in Child table.
db.Users.Add(user);
db.SaveChanges();
return ReidrectToAction("Index"); //PRG pattern
}
return View(vmModel);
}