Username availability and insert new user

后端 未结 2 1427
一个人的身影
一个人的身影 2020-12-22 06:19

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

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-22 06:33

    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);
    }
    

提交回复
热议问题