2

我有这个问题:

我正在验证一个模型,其中 2 个属性的总和不能大于 100。为此,我使用如下:

在我的模型中,这些是我的属性:

[Remote("ValidatePrevTextWidth", "Validation", AdditionalFields = "TextboxWidth")]
    public int PrevTextWidth { get; set; }

[Remote("ValidateTextboxWidth", "Validation", AdditionalFields = "PrevTextWidth")]
    public int TextboxWidth { get; set; }

我的 ValidationController 如下:

public JsonResult ValidatePrevTextWidth(int PrevTextWidth, int TextboxWidth)
    {
        bool valid = AreValid(PrevTextWidth, TextboxWidth);
        return Json(valido, JsonRequestBehavior.AllowGet);
    }

public JsonResult ValidateTextboxWidth(int TextboxWidth, int PrevTextWidth)
    {            
        bool valid = AreValid(PrevTextWidth, TextboxWidth);
        return Json(valido, JsonRequestBehavior.AllowGet);
    }

private bool AreValid(int prevTextWidth, int textboxWidth)
    {
        return (prevTextWidth + textboxWidth)<=100;
    }

我的看法如下:

@using (Html.BeginForm("Index", "Pregunta", FormMethod.Post, new { id = "frmNewPreguntaDesign" }))
{ @Html.TextBoxFor(m => m.PrevTextWidth) 
  @Html.TextBoxFor(m => m.TextboxWidth)
}

这很好用。问题如下:假设prevTextWidth用户插入的是55,然后他插入46textboxWidth,这里验证失败,textboxWidth并且突出显示。

但是如果现在用户将 prevTextWidth 的 de 值更改为 54 会发生什么?验证赢得了t fail, but thetextboxWidth will continue to be highlighted and not valid. The only way to make it valid is to re-insert the value oftextboxWidth`。

那么有没有办法同时验证两个属性,而不是重新插入第二个值以使其有效?

提前致谢,

马蒂亚斯

4

1 回答 1

0

Unfortunately the remote validator only uses the additional field to get the value of that field - it doesn't trigger the validation when that additional field is changed. The JQuery EqualTo (CompareAttribute in MVC) does the same thing.

One way you could achieve what you want is to write a little bit of javascript to validate the first field when the additional field is changed e.g.

 $('#PrevTextWidth').change(function () {
    $('#TextboxWidth').valid();
});
于 2011-11-10T09:43:46.527 回答