gpt4 book ai didi

asp.net-mvc-3 - 在 ASP.NET MVC3 中,如何手动对生成的属性应用验证

转载 作者:行者123 更新时间:2023-12-01 16:08:41 26 4
gpt4 key购买 nike

情况是这样的,我在数据库中定义了大约 20 个属性(称为属性)的列表。这包括一个名称、可能的值、一个可选的正则表达式、一个指示该字段是必需的 bool 值等。

在我的 ViewModel 中,我得到了属性列表,在我的 List View 中,我有一个很好的 AttributeViewModel EditorTemplate,可以使用 Steve Sanderson 的酷 BeginCollectionItem 来显示它们。确保帖子被绑定(bind)回 AttributeViewModel 列表(这工作得很好)。

我的 AttributeViewModel 看起来像这样:

public class AttributeViewModel
{
public string Description { get; set; }
public IEnumerable<SelectListItem> Values { get; set; }
public string SelectedValue { get; set; }
public byte RenderAs { get; set; }
public int AttributeID { get; set; }
public int ID { get; set; }
public int RegexValidation { get; set; }
public bool IsRequired { get; set; }
}

我的 View 看起来像这样 (edit.cshtml):

@model Company.Services.ViewModels.StaffMemberViewModel

<h2>Edit</h2>
@using (Html.BeginForm())
{
Some fields here, nothing of interest.

@Html.EditorFor(model => model.AttributeValues)

<input type="submit" value="Send" />
}

不过,这是有趣的一点,这是我的 AttributeValues 编辑器模板:

@using Company.Web.Helpers // This is where "BeginCollectionItem" lives
@model Company.Services.ViewModels.AttributeViewModel

using (Html.BeginCollectionItem("attributes"))
{
<div class="editor-label">
@Model.Description
</div>
<div class="editor-field">
@Html.DropDownListFor(m => m.SelectedValue, new SelectList(Model.Values, "Value", "Text"), "-- Select --")
@Html.HiddenFor(model => model.AttributeID)
</div>
}

我想做的是使用 IsRequired 和 RegexValidation 来确保每个属性的 SelectedValue 有效。我将如何去做呢?如果可能的话,我真的很想像我“通常”那样利用 MVC3 验证框架和不显眼的验证。

我显然不能动态添加 RequiredAttribute 或 RegularExpressionAttribute,因为列表中的每个属性对象都不同。

最佳答案

这是未经测试的。您可能需要尝试一下才能获得想要的结果。

首先,创建您的自定义 DataAnnotationsModelValidatorProvider 类:

public class MyModelMetadataValidatorProvider : DataAnnotationsModelValidatorProvider
{
internal static DataAnnotationsModelValidationFactory DefaultAttributeFactory = Create;
internal static Dictionary<Type, DataAnnotationsModelValidationFactory> AttributeFactories =
new Dictionary<Type, DataAnnotationsModelValidationFactory>()
{
{
typeof(RequiredAttribute),
(metadata, context, attribute) => new RequiredAttributeAdapter(metadata, context, (RequiredAttribute)attribute)
},
{
typeof(RegularExpressionAttribute),
(metadata, context, attribute) => new RegularExpressionAttributeAdapter(metadata, context, (RegularExpressionAttribute)attribute)
}
};

internal static ModelValidator Create(ModelMetadata metadata, ControllerContext context, ValidationAttribute attribute)
{
return new DataAnnotationsModelValidator(metadata, context, attribute);
}

protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
{
List<ModelValidator> vals = base.GetValidators(metadata, context, attributes).ToList();
if (metadata.ModelType.Name == "SelectedValue")
{
// get our parent model
var parentMetaData = ModelMetadataProviders.Current.GetMetadataForProperties(context.Controller.ViewData.Model,
metadata.ContainerType);

// get the associated AttributeId
var attributeId = Convert.ToInt32(parentMetaData.FirstOrDefault(p => p.PropertyName == "AttributeId").Model);

// get AttributeViewModel with specified AttributeId from repository
var attributeViewModel = _db.AttributeViewModels.FirstOrDefault(x => x.AttributeId == attributeId);

DataAnnotationsModelValidationFactory factory;

// check if required
if (attributeViewModel.IsRequired)
{
// must be marked as required
var required = new RequiredAttribute();
required.ErrorMessage = attributeViewModel.Description.Trim() +
" is Required";
if (!AttributeFactories.TryGetValue(required.GetType(), out factory))
factory = DefaultAttributeFactory;

vals.Add(factory(metadata, context, required));
}

// check for regex
if (attributeViewModel.RegexValidation > 0)
{
// get regex from repository
var regexValidation = _db.attributeViewModels.
FirstOrDefault(x => x.RegexValidation == attributeViewModel.RegexValidation);
var regex = new RegularExpressionAttribute(regexValidation.Pattern);
regex.ErrorMessage = attributeViewModel.Description.Trim() +
" is not in a valid format";
if (!AttributeFactories.TryGetValue(regex.GetType(), out factory))
factory = DefaultAttributeFactory;

vals.Add(factory(metadata, context, regex));
}
}
return vals.AsEnumerable();
}
}

然后,将以下内容添加到 Global.asax.cs 中的 Application_Start:

ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(new MyModelMetadataValidatorProvider());

关于asp.net-mvc-3 - 在 ASP.NET MVC3 中,如何手动对生成的属性应用验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8297316/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com