使用一个接口作为一个局部视图+数据注解的机型 [英] Using an interface as the model type of a partial view + data annotations

查看:148
本文介绍了使用一个接口作为一个局部视图+数据注解的机型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在哪里取决于局部视图被用在一个复杂的局部视图需要的字段不同的验证情况。

I have a case where a complex partial view needs different validation of fields depending on where the partial view is used.

我以为我能解决这个问题通过使局部视图需要一个接口作为型号和实现基于接口的两种不同的ViewModels。在这两个的ViewModels数据注释会有所不同。然后我会提供正确的视图模型的实例的局部视图。

I thought I could get around this by making the partial view take an interface as the model type and implementing two different ViewModels based on the interface. The data annotations in the two ViewModels would be different. I would then supply an instance of the correct ViewModel to the partial view.

但我发现是被认可的唯一注解是那些接口本身。在接口实现视图模型类的DA被忽略,即使是那些正在为模型传递的对象。所以,我的计划是行不通的。

But what I'm finding is that the only annotations that are recognized are those on the interface itself. DAs on the interface-implementing ViewModel classes are ignored, even though those are the objects that are being passed as models. So my plan isn't working.

有没有办法解决?一个更好的办法?我想preFER不是局部视图拆分成独立的意见,如果我能避免它。

Is there a way around this? A better approach? I'd prefer not to split the partial view into separate views if I can avoid it.

ETA:这是部分视图的简化版本,要求:

ETA: This is an abbreviated version of the partial view, as requested:

@model IPerson
@Html.ValidationSummary(false)
<fieldset>
    <table class="editForm">
        <tr>
            <td class="editor-label">
                @Html.LabelFor(model => model.FirstName)
            </td>
            <td class="editor-field">
                @Html.EditorFor(model => model.FirstName)
                @Html.ValidationMessageFor(model => model.FirstName)
            </td>
            <td class="editor-label">
                @Html.LabelFor(model => model.LastName)
            </td>
            <td class="editor-field">
                @Html.EditorFor(model => model.LastName)
                @Html.ValidationMessageFor(model => model.LastName)
            </td>
        </tr>
     </table>
  <fieldset>

真正的局部视图是很长,有很多@if报表管理可选部分的呈现(或没有),但它不会做任何事情棘手。

The real partial view is quite long and has a lot of @if statements managing the rendering (or not) of optional sections, but it doesn't do anything tricky.

推荐答案

我的想法是行不通的:<一href=\"http://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/1748587a-f13c-4dd7-9fec-c8d57014632c/\"相对=nofollow>此线程提醒我说,类不继承从各自的接口属性。 (作为回答指出,如果将两个接口指定具有不同属性相同的属性都出自一人之类实现发生什么,和?)

My idea isn't going to work: this thread reminded me that classes don't inherit attributes from their interfaces. (As the answer points out, what would happen if two interfaces specified the same property with different attributes, and both were implemented by one class?)

这可能与公共基类的工作。我会尝试明天。

It might work with a common base class. I will try that tomorrow.

谢谢大家。

这篇关于使用一个接口作为一个局部视图+数据注解的机型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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