Asp.net mvc 寻求一种可重用的MVC后代码模型

Asp.net mvc 寻求一种可重用的MVC后代码模型,asp.net-mvc,validation,data-annotations,asp.net-mvc-5,dry,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 posta

我在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);
                }
            });
        }
    });
}

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


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

p.s.我考虑过的一个可能的解决方案是创建一个只包含一个字段的共享子ViewModel。我怀疑在将来的某个时候绑定某些东西最终会让我感到悲伤,但这是我目前唯一的想法。正如我所怀疑的那样,我尝试了这个方法,但要求邮政编码很难看。你如何确保新的viewmodel不为空?使用合理的验证消息在每个视图上放置一个“Required”属性,并向父视图添加一个“ValidationMessageFor”?根据这个问题:如果您有一个[Required],我通常在父视图模型默认构造函数中初始化子视图模型在您的子viewmodel属性上,提交表单时将触发验证。这将起作用。别误会,我很感激你的回答。这种事情只会暴露出平台的弱点。当我完成的时候,我将拥有几乎和我正在抽象的代码一样多的抽象代码。