ASP.NET MVC 中的模型警告 [英] Model Warnings in ASP.NET MVC

查看:19
本文介绍了ASP.NET MVC 中的模型警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在 asp.net mvc 中使用 ModelStateDictionary 来保存验证错误,然后将其传回给用户.特别是能够使用 ModelState.IsValid 检查整个模型是否有效.但是,我正在处理的当前应用程序需要能够报告警告.这些并不重要,因此仍可以保存表单内容,但应将它们显示给用户,以便可以选择采取行动.

I'm currently using the ModelStateDictionary in asp.net mvc to hold validation errors and pass then back to the user. Being able to check if the whole model is valid with ModelState.IsValid is particularly. However, a current application I'm working on has a need to be able to report warnings. These aren't as critical so the form content can still be saved, but they should be shown to the user so that action can be optionally taken.

我一直在查看框架,看看是否有任何明显的地方可以扩展它以允许我这样做.我在想另一本带有警告的字典和一个称为模型警告的模型错误子类.我不确定如何让框架在视图等中使用我的新容器类.不过,我仍然希望所有现有的错误内容都能正常工作.

I've been looking through the framework to see if there are any obvious place to extend it to allow me to do this. I'm thinking that another dictionary with warnings in and a subclass of model error called model warning. I'm not sure how I'd get the framework to use my new container classes in the view etc. though, I still want all of the existing error stuff to work.

如果有人尝试过类似的事情或有任何想法,我会很感激他们的意见.

If anyone has tried anything similar or has any thoughts I'd appreciate their input.

更新:

我已经扩展了 ViewDataDictionary 以添加一些警告

I've got as far as extending the ViewDataDictionary to add some warnings

public class AetherViewDataDictionary : ViewDataDictionary
{
    public AetherViewDataDictionary()
    {
        ModelStateWarning = new ModelStateDictionary();
    }

    public AetherViewDataDictionary(object model) : base(model)
    {
        ModelStateWarning = new ModelStateDictionary();
    }

    public AetherViewDataDictionary(ViewDataDictionary viewDataDictionary) : base(viewDataDictionary) 
    {
        ModelStateWarning = new ModelStateDictionary();
    }

    public ModelStateDictionary ModelStateWarning { get; private set; }
}

我现在遇到的问题是,当我到达我的视图代码时,这只是为了调试,我失去了它是我的新类型的事实,所以当我尝试将它转换回来并访问我的新字典我没有快乐.

The problem that I'm having now is that when I get to my view code, this is just for debug I'm losing the fact that its my new type, so when I try to cast it back and get access to my new dictionary I have no joy.

public partial class Index : ViewPage<PageViewData>
{
    protected override void SetViewData(ViewDataDictionary viewData)
    {
        base.SetViewData(viewData);
    }
}

它在这里设置正确,但是当我检查类型时它不见了.

It sets it correctly here, but when I check the type its gone.

结果证明这是一种愚蠢的做事方式,请参阅下面的答案.

This turned out to be a dumb way of doing things, see answer below.

推荐答案

所以我之前的路线是一个坏主意,只是框架中没有足够的访问权限来获取那些位你需要.至少要重新发明轮子几次.

So the route that I was headed down before turned out to be a bad idea, there just isn't enough access in the framework to get at the bits that you need. At least not without reinventing the wheel a few times.

我决定继续扩展 ModelState 类以向其添加警告集合:

I decided to head down the route of extending the ModelState class to add a warnings collection to it:

public class AetherModelState : ModelState
{
    public AetherModelState() { }

    public AetherModelState(ModelState state)
    {
        this.AttemptedValue = state.AttemptedValue;

        foreach (var error in state.Errors)
            this.Errors.Add(error);
    }

    private ModelErrorCollection _warnings = new ModelErrorCollection();

    public ModelErrorCollection Warnings { get { return this._warnings; } }
}

为了能够像添加错误一样轻松添加警告,我为 ModelStateDictionary 创建了一些扩展方法:

In order to be able to easily add warnings in the same way that you would errors I created some extension methods for the ModelStateDictionary:

public static class ModelStateDictionaryExtensions
{
    public static void AddModelWarning(this ModelStateDictionary msd, string key, Exception exception)
    {
        GetModelStateForKey(key, msd).Warnings.Add(exception);
    }

    public static void AddModelWarning(this ModelStateDictionary msd, string key, string errorMessage)
    {
        GetModelStateForKey(key, msd).Warnings.Add(errorMessage);
    }

    private static AetherModelState GetModelStateForKey(string key, ModelStateDictionary msd)
    {
        ModelState state;
        if (string.IsNullOrEmpty(key))
            throw new ArgumentException("key");

        if (!msd.TryGetValue(key, out state))
        {
            msd[key] = state = new AetherModelState();
        }

        if (!(state is AetherModelState))
        {
            msd.Remove(key);
            msd[key] = state = new AetherModelState(state);
        }

        return state as AetherModelState;
    }

    public static bool HasWarnings(this ModelStateDictionary msd)
    {
        return msd.Values.Any<ModelState>(delegate(ModelState modelState)
        {
            var aState = modelState as AetherModelState;
            if (aState == null) return true;
            return (aState.Warnings.Count == 0);
        });
    }
}

GetModelStateForKey 代码很复杂,但您应该能够看到我的目标.接下来要做的是编写一些扩展方法,允许我显示警告和错误

The GetModelStateForKey code is ropey but you should be able to see where I'm headed with this. The next thing to do is to write some extension methods that allow me to display the warnings along with the errors

这篇关于ASP.NET MVC 中的模型警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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