在Asp.net MVC 3中验证和编辑" Changeable" / optional类型

时间:2011-11-06 12:43:06

标签: c# asp.net asp.net-mvc asp.net-mvc-3

对于项目,我需要一种方法来指定属性是否已更改。

所以在模型中我想要以下内容:

public class Changeable<T>
{
   public bool Changed { get; set; }
   public T Value { get; set; }
}

public class MyModel
{
    [Range(1, 10)]
    public Changeable<int> SomeInt { get; set; }
}

查看:

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

然后我将生成一个带有textfield(int)和一个复选框(已更改)的编辑器。 选中复选框时应调用验证属性(Range等),但取消选中时不应调用。

我尝试使用Changeable的editortemplate进行上述操作(然后是验证,模型绑定等),但我已经因编辑项目而丢失了,因为它不能是通用的。

我想要的解决方案是否可行,还是有另一种合理的优雅解决方案?

现在我正在开发一个带有属性string[] ChangedProperties的解决方案和大量的Javascript来处理验证等,但它相当丑陋且远未完成。

...谢谢

3 个答案:

答案 0 :(得分:2)

您可以尝试使用具有自定义范围验证属性的动态类型:

public interface IChangeable
{
    bool Changed { get; set; }
}

public class Changeable<T> : IChangeable
{
    public bool Changed { get; set; }
    public T Value { get; set; }
}

public class MyModel
{
    [MyRange(1, 10)]
    public Changeable<int> SomeInt { get; set; }
}

public class MyRangeAttribute : RangeAttribute
{
    public MyRangeAttribute(double minimum, double maximum): base(minimum, maximum)
    { }

    public MyRangeAttribute(int minimum, int maximum)
        : base(minimum, maximum)
    { }

    public override bool IsValid(object value)
    {
        var changeable = value as IChangeable;
        if (changeable == null || !changeable.Changed)
        {
            return true;
        }
        dynamic dynValue = value;

        return base.IsValid((object)dynValue.Value);
    }
}

然后是控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyModel
        {
            SomeInt = new Changeable<int>
            {
                Changed = true,
                Value = 5
            }
        });
    }

    [HttpPost]
    public ActionResult Index(MyModel model)
    {
        return View(model);
    }
}

然后是一个视图(~/Views/Home/Index.cshtml):

@model MyModel

@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.SomeInt)
    <button type="submit">OK</button>
}

和相应的编辑器模板(注意编辑器模板文件的名称)

~/Views/Shared/EditorTemplates/Changeable`1.cshtml

@model dynamic
@Html.CheckBox("Changed", (bool)Model.Changed)
@Html.Editor("Value")
@Html.ValidationMessage("")

答案 1 :(得分:1)

我被这个问题着迷,我花了很多时间思考你的目标。我昨天有一个突破,我有一些代码可以完成你几乎所有的目标。

您曾说过,只有在选中Changed时才需要启动验证器。此代码总是触发验证器,因为我认为阻止验证器触发是一个好习惯。代码所做的是检查用户是否更改了值,并在发生这种情况时自动检查Changed。如果用户取消选中已更改复选框,则旧值将放在Value框中。

代码由HTML帮助程序,ModelMetadataProvider,ModelBinder和一些小的javascript组成。在代码之前,这里是已定义的模型,与Darin相同,添加了一个额外的属性:

public interface IChangeable
{
    bool Changed { get; set; }
}

public class Changeable<T> : IChangeable 
{
    public bool Changed { get; set; }
    public T Value { get; set; }
}

public class MyModel
{
    [Range(1, 10), Display(Name = "Some Integer")]
    public Changeable<int> SomeInt { get; set; }

    [StringLength(32, MinimumLength = 6), Display(Name = "This String")]
    public Changeable<string> TheString { get; set; }
} 

从HTML帮助程序开始:

public static class HtmlHelperExtensions
{
    public static MvcHtmlString ChangeableFor<TModel, TValue, TType>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, Changeable<TType> changeable)
    {
        var name = ExpressionHelper.GetExpressionText(expression);
        if (String.IsNullOrEmpty(name)) 
            throw new ArgumentNullException("name", "Name cannot be null");

        var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
        var type = metadata.ModelType;
        var containerType = metadata.ContainerType;
        var arg = Expression.Parameter(containerType, "x");
        Expression expr = arg;
        expr = Expression.Property(expr, name);
        expr = Expression.Property(expr, "Value");
        var funcExpr = Expression.Lambda(expr, arg) as Expression<Func<TModel, TType>>;
        var valueModelMetadata = ModelMetadata.FromLambdaExpression(funcExpr, html.ViewData);

        Expression exprChanged = arg;
        exprChanged = Expression.Property(exprChanged, name);
        exprChanged = Expression.Property(exprChanged, "Changed");
        var funcExprChanged = Expression.Lambda(exprChanged, arg) as Expression<Func<TModel, bool>>;

        var htmlSb = new StringBuilder("\n");
        htmlSb.Append(LabelExtensions.Label(html, metadata.GetDisplayName()));
        htmlSb.Append("<br />\n");
        htmlSb.Append(InputExtensions.CheckBoxFor(html, funcExprChanged));
        htmlSb.Append(" Changed<br />\n");
        htmlSb.Append(InputExtensions.Hidden(html, name + ".OldValue", valueModelMetadata.Model) + "\n");
        htmlSb.Append(EditorExtensions.EditorFor(html, funcExpr, new KeyValuePair<string, object>("parentMetadata", metadata)));
        htmlSb.Append(ValidationExtensions.ValidationMessageFor(html, funcExpr));
        htmlSb.Append("<br />\n");

        return new MvcHtmlString(htmlSb.ToString());
    }
}

这将父元数据传递到ViewData(这将允许我们稍后获取类验证器)。它还创建了lambda表达式,因此我们可以使用CheckBoxFor()EditorFor()。使用我们的模型和这个帮助器的视图如下:

@model MyModel 
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@using (Html.BeginForm())
{
    <script type="text/javascript">
        $(document).ready(function () {
            $("input[id$='Value']").live("keyup blur", function () {
                var prefix = this.id.split("_")[0];
                var oldValue = $("#" + prefix + "_OldValue").val();
                var changed = oldValue != $(this).val()
                $("#" + prefix + "_Changed").attr("checked", changed);
                if (changed) {
                    // validate
                    $(this.form).validate().element($("#" + prefix + "_Value")[0]);
                }
            });

            $("input[id$='Changed']").live("click", function () {
                if (!this.checked) {
                    // replace value with old value
                    var prefix = this.id.split("_")[0];
                    var oldValue = $("#" + prefix + "_OldValue").val();
                    $("#" + prefix + "_Value").val(oldValue);
                    // validate
                    $(this.form).validate().element($("#" + prefix + "_Value")[0]);
                }
            });
        });
    </script>

    @Html.ChangeableFor(x => x.SomeInt, Model.SomeInt)
    @Html.ChangeableFor(x => x.TheString, Model.TheString)

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

注意javascript用于处理Value文本框的更改并单击Changed复选框。另请注意,需要将Changeable<T>属性两次传递给ChangeableFor()帮助程序。

接下来,自定义ModelValidatorProvider:

public class MyDataAnnotationsModelValidatorProvider : DataAnnotationsModelValidatorProvider
{
    private bool _provideParentValidators = false;

    protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
    {
        if (metadata.ContainerType != null && metadata.ContainerType.Name.IndexOf("Changeable") > -1 && metadata.PropertyName == "Value")
        {
            var viewContext = context as ViewContext;
            if (viewContext != null)
            {
                var viewData = viewContext.ViewData;
                var index = viewData.Keys.ToList().IndexOf("Value");
                var parentMetadata = viewData.Values.ToList()[index] as ModelMetadata;
                _provideParentValidators = true;
                var vals = base.GetValidators(parentMetadata, context);
                _provideParentValidators = false;
                return vals;
            }
            else
            {
                var viewData = context.Controller.ViewData;
                var keyName = viewData.ModelState.Keys.ToList().Last().Split(new string[] { "." }, StringSplitOptions.None).First();
                var index = viewData.Keys.ToList().IndexOf(keyName);
                var parentMetadata = viewData.Values.ToList()[index] as ModelMetadata;
                parentMetadata.Model = metadata.Model;
                _provideParentValidators = true;
                var vals = base.GetValidators(parentMetadata, context);
                _provideParentValidators = false;
                return vals;
            }
        }
        else if (metadata.ModelType.Name.IndexOf("Changeable") > -1 && !_provideParentValidators)
        {
            // DO NOT provide parent's validators, unless it is at the request of the child Value property
            return new List<ModelValidator>();
        }
        return base.GetValidators(metadata, context, attributes).ToList();
    }
}

请注意,根据我们是在填充视图还是在POST上绑定模型,有不同的方法来检查父元数据。另请注意,我们需要禁止父级接收验证器。

最后,ModelBinder:

public class ChangeableModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (controllerContext.Controller.ViewData.Keys.ToList().IndexOf(bindingContext.ModelName) < 0)
            controllerContext.Controller.ViewData.Add(bindingContext.ModelName, bindingContext.ModelMetadata);
        return base.BindModel(controllerContext, bindingContext);
    }
}

这将获取父元数据并将其存储起来,以便稍后在自定义ModelValidatorProvider中访问。

使用Global.asax.cs中的Application_Start完成以下内容:

ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(new MvcApplication5.Extensions.MyDataAnnotationsModelValidatorProvider());
MyDataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

ModelBinders.Binders.Add(typeof(MvcApplication5.Controllers.Changeable<int>), new ChangeableModelBinder());
ModelBinders.Binders.Add(typeof(MvcApplication5.Controllers.Changeable<string>), new ChangeableModelBinder());
// you must add a ModelBinders.Binders.Add() declaration for each type T you
// will use in your Changeable<T>

中提琴!

答案 2 :(得分:0)

我不是百分百肯定,但我认为你想要的是:

private int _changeable;

public Changeable<int> SomeInt { 
get 
    { return _changeable } 
set 
    { _changeable = value;
      Changed = true;
    }
}