服务器端远程验证未触发

时间:2017-06-03 08:38:03

标签: asp.net angularjs asp.net-mvc validation asp.net-web-api

我正在尝试验证 AccessoryType 的唯一性。我已将远程验证放入模型中。

这是代码设置,

在模型中,

public class AccessoryTypeMasterMetaData
{
    [Remote("checkAccessoryTypeExist", "AccessoryType")]
    [Required(ErrorMessage = "Please enter accessory type.")]
    [StringLength(20, ErrorMessage = "Please enter maximum of {1} characters in accessory type.")]

    public string AccessoryType { get; set; }
}

我在API控制器中放了** checkAccessoryTypeExist 方法,**

[HttpPost]
    [AllowAnonymous]
    [Route("api/AccessoryType/checkAccessoryTypeExist")]
    public IHttpActionResult checkAccessoryTypeExist(string accessoryType, int accessoryTypeID)
    {
        AccessoryTypeMasterService accessoryTypeMasterService = new AccessoryTypeMasterService();

        BaseResponseModel<bool> baseResponseModel = new BaseResponseModel<bool>();
        baseResponseModel.status = true;
        baseResponseModel.data = false;

        if (!string.IsNullOrEmpty(accessoryType))
        {
            baseResponseModel.data = accessoryTypeMasterService.CheckAccessoryType(accessoryType, accessoryTypeID);
            baseResponseModel.message = LES_Common.STATUS_SUCCESS;
        }

        return new BaseResponseResult<bool>(baseResponseModel, Request);

    }

所以问题是远程验证没有在服务器端触发 但其他所有验证都是触发(如Required,StringLength)

我的代码有问题吗?帮帮我......

1 个答案:

答案 0 :(得分:0)

在方法声明中,有两个参数accessoryType , accessoryTypeID。在AccessoryTypeMasterMetaData模型中,您只能将其应用于AccessoryType。因此,如果您需要额外accessoryTypeID来检查,那么您将只获得AccessoryType值,然后您需要在属性上更改RemoteAttribute,如下所示:

[Remote("checkAccessoryTypeExist", "AccessoryType",HttpMethod = "POST", AdditionalFields = nameof(AccessoryTypeID ), ErrorMessage = "Error message to display." )]

如果您将方法签名更改为:

,情况会更好
public IHttpActionResult checkAccessoryTypeExist(AccessoryTypeMasterMetaData modelData)
    {


 // You can access it here i.e. modelData.AccessoryType and modelData.AccessoryTypeID

    }