2

我尝试在 EditorFor 中验证字符串。如果许可证不在我的数据库中,我想打印一个错误。

这是我的模型:

    [Display(Name = "Lizenznummer")] 
    [Required]
    [Remote("IsLicenseValid", "HLRController", "Lizenznummer ungültig")]    
    public string HLR_LIZENZ { get; set; }

这是我的控制器(HLRController.cs)

    public ActionResult IsLicenseValid(string HLR_LIZENZ)
    {
        return IsExist(HLR_LIZENZ)
            ? Json(true, JsonRequestBehavior.AllowGet)
            : Json(string.Format("{0} ist nicht gültig.", HLR_LIZENZ),
                    JsonRequestBehavior.AllowGet);
        //: Json(false, JsonRequestBehavior.AllowGet);


    }

    public bool IsExist(string license)
    {
        bool result = false;

        var item = (from c in db.KD select c).ToArray();

        for (int i = 0; i < item.Length; i++)
        {
            if (item[i].KD_LIZENZ == license)
                result = true;

            if (result)
                break;
        }           

        return result;
    }

还有我的观点:

    <div class="editor-field">
    @Html.EditorFor(model => model.HLR_LIZENZ)
    @Html.ValidationMessageFor(model => model.HLR_LIZENZ)
    </div>

我不知道我哪里出错了。我在这里和互联网的其他页面上看到了类似的代码-.-

如果我测试这段代码,什么都不会发生。好吧,没有什么是谎言。如果我在我的 EditFor 中写了一个许可证,什么也不会发生 - 但是 [Required] Vaidation 不起作用。如果该字段为空,他将写入 ErrorMessage 并将该字段框为红色。然后我输入了一些东西——红框消失了,但 ErrorMessage 仍然存在。

我想对此进行调试,并在我的“IsLicenseValid”方法中放置了一个断点——但他并没有就此止步。所以这种方法从未被使用过..(?!)

有人有想法吗?非常感谢!

4

1 回答 1

2

You have to omit controller part in the controller name of your attribute, it is handled by the framework:

[Remote("IsLicenseValid", "HLR", "Lizenznummer ungültig")]
于 2014-08-14T06:00:21.217 回答