我可以使用MVC 5远程验证来检查重复值,但排除正在编辑的项目吗?

时间:2018-12-13 20:39:46

标签: c# asp.net-mvc

我已经为表单设置了一些验证,以检查输入的序列号是否已经存在。这非常适合创建项,但是编辑项并提交时,它不能识别出已编辑的项具有导致该问题的序列号。是否可以通过IsSerialAvailable操作识别用户正在编辑项目,而忽略该值?

注释:

[Display(Name = "Serial #")]
[Remote("IsSerialAvailable", "Item", ErrorMessage = "Serial # already exists.")]
public string Serial { get; set; }

控制器代码:

public ActionResult IsSerialAvailable(string Serial)
    {
        using (db)
        {
            try
            {
                var serial = db.Items.Single(i => i.Serial == Serial);
                return Json(false, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }
        }
    }

2 个答案:

答案 0 :(得分:1)

因此,您将需要2个视图模型。一种用于创建,另一种用于编辑。通过传递项目ID,我们知道它是一个编辑,如果没有过去,我们就知道它是一个创建。

public class CreateItemViewModel
{
    [Remote("IsSerialAvailable", "Value")]
    public string Serial { get; set; }
}

public class EditItemViewModel
{
    [Remote("IsSerialAvailable", "Value", AdditionalFields = "ItemId")]
    public string Serial { get; set; }

    public int ItemId { get; set; }
}

    public ActionResult IsSerialAvailable(string serial, int? itemId = null)
    {
        List<int> t = new List<int>();

        Item item;

        if (itemId.HasValue)
        {
            item = db.Items.SingleOrDefault(i => i.Serial == Serial && i.Id != itemId.Value);

        }
        else
        {
            item = db.Items.SingleOrDefault(i => i.Serial == Serial);
        }

        if (item != null)
        {
            return Json(false, JsonRequestBehavior.AllowGet);
        }

        return Json(true, JsonRequestBehavior.AllowGet);
    }

答案 1 :(得分:0)

您可以获取操作名称,以查看请求来自创建还是编辑。

public ActionResult IsSerialAvailable(string Serial)
    {
        using (db)
        {
            try
            {
                var actionName = HttpContext.Request.UrlReferrer.Segments[2];
                var serial = db.Items.Single(i => i.Serial == Serial);
                return Json(false, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }
        }
    }

但是我推荐的是自定义验证

http://dotnetmentors.com/mvc/how-to-do-custom-validation-using-validationattribute-of-aspnet-mvc.aspx