MVC自动完成验证 [英] MVC Autocomplete validation

查看:56
本文介绍了MVC自动完成验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的MVC应用程序中,我有一个使用JQuery / AJAX自动完成的View,其中这是一个摘录;

In my MVC app I have this View that uses JQuery/AJAX autocomplete, of which this is an extract;

<input type="search" name="searchPrimaryTrade" id="searchPrimaryTrade" 
       data-scd-autocomplete="@Url.Action("AutocompletePrimaryTrade", "DataService")" 
       style = "width: 300px;" data-val="true" class="primaryTrade required" data-val-required="Must enter a Primary Trade"     />
<input type="button" id="ResetPrimaryTrade" value="Reset" class="resetSearch" data-scd-target-searchId="searchPrimaryTrade" style="margin-top:-6px; height:30px;"/><br/>
@Html.HiddenFor(model => model.PrimaryTradeId)
@Html.ValidationMessageFor(model => model.PrimaryTradeId, "*")

当用户选择一个项目进行自动完成时,我使用JQuery来填充隐藏字段; @ Html.HiddenFor(model => model.PrimaryTradeId)

When the user selects an item for autcomplete, I use JQuery to populate the hidden field; @Html.HiddenFor(model => model.PrimaryTradeId).

我的老板告诉我,如果用户在此字段中输入值,但未从自动填充中选择,然后当他点击该字段时,应立即显示错误消息。

My boss has told me that if the user enters a value in this field, but not selected from autocomplete, then when he clicks out of that field, an error message should display straight away.

如何实施那个?

推荐答案

你可以像这样创建一个自定义验证属性:

You can create a custom validation attribute like this:

public class PrimaryTradeAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        if (value != null && value is int)
        {
            var unitOfWork = new UnitOfWork();
            int primaryTradeId = (int)value;

            // Code to check if the PrimaryTradeId exists in the database...
            if (unitOfWork.PrimaryTradeRepository().Find(primaryTradeId) == null)
            {
                return false;
            }
        }

        return true;
    }
}

然后,您可以在模型中使用此属性这个:

Then, you can use this attribute in your Model like this:

[PrimaryTrade]
public int PrimaryTradeId { get; set; }

这篇关于MVC自动完成验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆