验证 - 用户已添加,MVC 4

时间:2014-12-04 09:57:33

标签: asp.net asp.net-mvc asp.net-mvc-4 validation

我试图在我的代码中添加验证。

当我输入用户名并再次尝试时,我收到错误提示违反PRIMARY KEY约束

因为我有2个主键(serialnumber和productNumber)所以我不能第二次添加用户,但是当我这样做时,我会得到一个错误页面。

但实际上我想要一条消息说已经添加了用户或该行中的某些内容。

Iv尝试了一些令人难以置信的答案,但却绕圈而行,所以我想问你们。

这是我的代码

型号:

    public string SerialNumber { get; set; }
    public string ProductNumber { get; set; }

    [Required(ErrorMessage = "Before you submit you must enter a valid UserName!")]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    [Display(Name = "Username")]
    public string UserName { get; set; }

    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    [Display(Name = "Alternative Username")]
    public string AltUserName { get; set; }

    public ReadingsUsersForm(string Ser_Num)
    {
        SerialNumber = Ser_Num;
        ProductNumber = cpctx.CustomerReadingsEntries.Where(s => s.ser_num == SerialNumber).Select(c => c.prod_um).FirstOrDefault();
        UserName = null;
        AltUserName = null;  
    }

控制器:

    [HttpPost]
    public ActionResult Save(EntrtyForm form)
    {

        var addForm = new M2CPDAL.Models.CustomerPortal.SerialUser();
        addForm.ser_num = form.SerialNumber;
        addForm.prod_num = form.ProductNumber;

        addForm.UserName = form.UserName;
        addForm.AltUserName = form.AltUserName;
        cp.SerialUsers.Add(addForm);
        cp.SaveChanges();

        return RedirectToAction("Index");
    }   

        public PartialViewResult GetAddEditReadings(string ser_num, string prod_num)
    {
        var model = new  AddEditReadingsViewModel(id, ser_num, prod_num, uProfile.CustNums);

        return PartialView("_ReadingsUsers", model);
    }

html代码:

@using (Html.BeginForm("Save", "Device", FormMethod.Post, new { enctype = "multipart/form-data" }))

{

<fieldset>
    <legend>Meter Reading Details</legend>

    <div>
        @Html.LabelFor(m => m.SerialNumber)
        @Html.TextBoxFor(m => m.SerialNumber, new { @class = "form", @readonly = "readonly" })
        @Html.ValidationMessageFor(m => m.SerialNumber)
    </div>
    <div>
        @Html.LabelFor(m => m.ProductNumber)
        @Html.TextBoxFor(m => m.ProductNumber, new { @class = "form", @readonly = "readonly" })
        @Html.ValidationMessageFor(m => m.ProductNumber)
    </div>

    <div>
        @Html.LabelFor(m => m.UserName)
        @Html.TextBoxFor(m => m.UserName, new { @id = "newColourReading", @class = "form-add" })
        @Html.ValidationMessageFor(m => m.UserName)
        <div id="ColourErrorMessage"></div>
   </div>

    <div>
        @Html.LabelFor(m => m.AltUserName)
        @Html.TextBoxFor(m => m.AltUserName, new { @id = "newColourReading", @class = "form-add2" })
        @Html.ValidationMessageFor(m => m.AltUserName)
        <div id="ColourErrorMessage"></div>

    </div>

    <div class="modal-footer">
        <input type="submit" id="ButtonSave" value="Submit" class="btn btn-primary">
        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
    </div>

}

etc...

所以在cp.SaveChanges()中;如果我第二次尝试添加用户,我将收到错误。

我可以遵循的任何想法或方向,我可以添加验证以检查是否已添加。

2 个答案:

答案 0 :(得分:1)

在Save方法中,只需添加一些代码来查找和输入此序列号和产品编号。如果有,请将用户发送到另一个页面

var exist = cp.SerialUsers.Where(x => x.serialNumber == form.serialNumber && x.productNumber == form.productNumber).FirstOrDefault()
if(exist!=null)
    return RedirectToAction("Exists"); 

答案 1 :(得分:1)

您无法使用标准验证属性解决此问题。你应该从你的数据库中得到答案。如果您可以通过一种方式在解决方案中使用它。

[HttpPost]
public ActionResult Save(EntrtyForm form)
{

    var addForm = new M2CPDAL.Models.CustomerPortal.SerialUser();
    var serialUser = cp.SerialUsers.FirstOrDefault(x => x.serialNumber == form.serialNumber && x.productNumber == form.productNumber);
    if(serialUser == null)
    {
      addForm.ser_num = form.SerialNumber;
      addForm.prod_num = form.ProductNumber;
      addForm.UserName = form.UserName;
      addForm.AltUserName = form.AltUserName;
      cp.SerialUsers.Add(addForm);
      cp.SaveChanges();
      return RedirectToAction("Index");
    }
    return RedirectToAction("serialUserExist");
}   

但如果您使用ModelState.IsValid

强类型化视图,则可以获得更好的解决方案
[HttpPost]
public ActionResult Save(EntrtyForm form)
{

    var addForm = new M2CPDAL.Models.CustomerPortal.SerialUser();
    var serialUser = cp.SerialUsers.FirstOrDefault(x => x.serialNumber == form.serialNumber && x.productNumber == form.productNumber);
    if(serialUser == null)
    {
      addForm.ser_num = form.SerialNumber;
      addForm.prod_num = form.ProductNumber;
      addForm.UserName = form.UserName;
      addForm.AltUserName = form.AltUserName;
      cp.SerialUsers.Add(addForm);
      cp.SaveChanges();
      return RedirectToAction("Index");
    }
    ModelState.AddModelError("SerialNumber", "Already Exist");
    var model = new AddEditReadingsViewModel(form);
    return PartialView("_ReadingsUsers", form);
}   

不要忘记从AddEditReadingsViewModel

创建初始化EntrtyForm的构造函数