为MVC寻求可重用的PostalCode模型

时间:2014-02-24 01:04:20

标签: asp.net-mvc validation data-annotations asp.net-mvc-5 dry

我在我的ASP.NET MVC网站的ViewModel中的邮政编码字段中使用了以下验证/演示文稿。我想在我的应用程序中与其他5个邮政编码编辑分享这个实现。如何避免重复此代码?

[Required]
[RegularExpression(LocationMatch.NorthAmericanPostalCodePattern,
    ErrorMessage = "You may look up cities here, but must submit a North American postal code")]
[Display(Name = "Postal Code", Prompt = "or type city")]
[Remote("ValidatePostalCode", "Utilities")]
[CustomValidation(typeof(CandidateMobileEditor), "ValidatePostalCode")]
public string PostalCode { get; set; }

public static ValidationResult ValidatePostalCode(string postalCode) {
    return LocationMatch.Closest(postalCode) == null ?
        new ValidationResult("Postal code not found") : null;
}

public void Load(Candidate sourceProfile) {
    PrimaryPostalCode = sourceProfile.Account.FormattedPostalCode;
}

public void Save(Candidate targetProfile) {
    targetProfile.Account.FormattedPostalCode = LocationMatch.Closest(PrimaryPostalCode).PostalCode;
}

此外,我还有以下与每个邮政编码字段相关联的JavaScript。为了完整起见,我提到了这一点,因为我知道有一些方法可以触发从公共代码激活它,但前提是我可以使用一些常见的自定义属性来加载或装饰模型。

singletons.lac = new locationAutocomplete("input[name='PrimaryPostalCode']");

function locationAutocomplete(selector) {
    var cache = {}, lastXhr;
    var locationField = $(selector);
    locationField.autocomplete({
        minLength: 5,
        delay: 0, // note the lookup delay is increased during the first search event
        search: function (event, ui) { locationField.autocomplete("option", "delay", 300); },
        change: function (event, ui) { locationField.change(); },
        source: function (request, response) {
            var term = request.term;
            if (term in cache) {
                response(cache[term]);
                return;
            }

            lastXhr = $.getJSON(SiteContext.VirtualRoot + "Utilities/GetMatchingLocations", request, function (data, status, xhr) {
                cache[term] = data;
                if (xhr === lastXhr) {
                    response(data);
                }
            });
        }
    });
}

1 个答案:

答案 0 :(得分:1)

专门为此邮政编码编辑器创建一个新的ViewModel,然后创建一个部分视图来保存所需的html和javascript。

当您需要使用此功能时,可以在ViewModel页面中包含此ViewModel,并使用@ Html.Partial(“您的邮件部分查看文件”)将其加载到您的页面中。