English 中文(简体)
动态检查模型的每个KeyValuePair值
原标题:Dynamically checking each KeyValuePair value of a model
  • 时间:2010-10-15 12:42:11
  •  标签:
  • c#
  • viewmodel

我有一个这样的视图模型,它是从我的验证器中创建的。

public class ViewModel
{
    public KeyValuePair<int, RuleType> Foo { get; set; }
    public KeyValuePair<string, RuleType> Bar { get; set; }
}

我的真实视图模型有20多个字段。一旦我的数据得到验证,一个类型为ViewModel的通用列表就会返回到我的MVC视图,并被处理成一个报告。然而,出现了一个功能请求,用户只希望看到带有错误和警告的模型,而不希望看到有效实体RuleType是一个枚举器。如果密钥对的所有值都是RuleType.Success,则模型有效。

是否可以遍历每个模型并检查RuleType,而不必手动检查每个属性?我的<code>GetAllModelsWithErrors()</code>函数将返回一个无效模型列表。我相信反思可能是一个解决方案,但我不确定这是否是一个好的解决方案。

最佳回答

试试这个:

    private IEnumerable<ViewModel> GetInvalidModels(ViewModel[] viewModels)
    {
        return 
            from viewModel in viewModels 
            from prop in typeof(ViewModel).GetProperties() 
            let ruleType = ((KeyValuePair<object, RuleType>)prop.GetValue(viewModel, null)).Value 
            where ruleType != RuleType.Success 
            select viewModel;
    }
问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签