我收到了一位上级的指令,要求使用远程验证而不是RequiredIf属性来检查某个字段是否有值,如果能够进行用户编辑的话。
现在,我的代码看起来像这样 -
查看模型
public class FooModel
{
// SNIP: Unimportant extra variables
public int? DeviceId;
public int? ProviderId;
[Remote("IsMessageRequired", "Foo",
AdditionalFields="DeviceId,CarrierId",
ErrorMessage="(required for other")]
public string MessageAddress { get;set; }
// SNIP: Unimportant other details
}
控制器
public class FooController
{
// SNIP: Unimportant details
public JsonResult IsMessageRequired(string messageAddress, int? device, int? carrier)
{
if(!string.IsNullOrEmpty(messageAddress))
return Json(true, JsonRequestBehavior.AllowGet);
// Conditions:
// A) Device = "Samsung" / Carrier = "Other"
// B) Device = "Other"
if(device = FooModel.GetDeviceIdByName("Samsung")
&& carrier = FooModel.GetProviderIdByName("Other")
{
return Json(! string.IsNullOrEmpty(pageAddress), JsonRequestBehavior.AllowGet);
}
if(device = FooModel.GetDeviceIdByName("Other"))
{
return Json(! string.IsNullOrEmpty(pageAddress), JsonRequestBehavior.AllowGet);
}
// Default condition occurs on first-run scenarios.
return Json(true, JsonRequestBehavior.AllowGet);
}
// SNIP: Other unimportant details
}
...最后,我的查看:
@model FooProject.Models.FooModel
@Html.DropDownFor(x => x.DeviceId)
@Html.DropDownFor(x => x.ProviderId)
@Html.TextBoxFor(x => x.MessageAddress)
@Html.ValidationMessageFor(x => x.MessageAddress)
问题:验证仅在输入值时触发,但从不在文本框中不包含任何值时触发。远程验证是否仅在文本框中有值时才有效?如果没有,我如何错误地接近此设置?
答案 0 :(得分:1)
它仅在$.trim
返回值时触发 - 因此对于所有非空和非空白值。