一个公共类中的必填字段和非必填字段

发布于 2024-12-11 22:36:49 字数 606 浏览 0 评论 0原文

我正在使用 ASP.NET MVC3,并且有以下类:

public class AddressMetadata
{
    public string State { get; set; }
    public string City { get; set; }
    public string Street { get; set; }
}

我还有以下编辑模型:

[Display(Name = "First Address")]
public Address FirstAddress { get; set; }
[Display(Name = "Second Address")]
public Address SecondAddress { get; set; }

我必须根据需要从 FirstAddress 创建所有字段,但不能从 SecondAddress 创建其他字段。

如何在不为第二个地址创建新类的情况下做到这一点?我知道我可以在 AddressMetadata 类中使用 [Required] 指令,但是如何在 FirstAddress 和 SecondAddress 之间划分这些规则?

I'm using ASP.NET MVC3 and I have the following class:

public class AddressMetadata
{
    public string State { get; set; }
    public string City { get; set; }
    public string Street { get; set; }
}

Also I have the following edit model:

[Display(Name = "First Address")]
public Address FirstAddress { get; set; }
[Display(Name = "Second Address")]
public Address SecondAddress { get; set; }

And I have to create all fields from FirstAddress as required, but the other ones from SecondAddress not.

How can I do that without creating new class for second address? I know that I can use [Required] directive in AddressMetadata class, but how can I divide those rules between FirstAddress and SecondAddress?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光病人 2024-12-18 22:36:50

我想这样的东西会起作用,但不是100%确定,我必须自己尝试一下。 (我实际上是从 EditorTemplates 开始)

  • 将 [Required] 添加到 EditModel 中的 FirstAddress。
  • 将 [Required] 添加到 Adress 类的所有属性。
  • 为 Address 类编写一个 TemplateEditor。

TemplateEditor 将使用 Address 作为其模型,并使用 Address 类注释对其进行验证,而视图将根据 EditModel 注释进行验证。

请原谅我糟糕的英语。

编辑:忘记了这一点:在视图中通过渲染 EditorTemplate

@Html.EditorFor (m => m.FirstAddress)

I guess something like this will work, not 100% sure, I've to try it myself. (I'm actually starting with EditorTemplates)

  • Add [Required] just to FirstAddress in the EditModel.
  • Add [Required] to all properties of the Adress class.
  • Write a TemplateEditor for Address class.

The TemplateEditor will have Address as its model and perform validation on that using Address class annotations, while the View will validate according to the EditModel annotations.

Please forgive me for my bad English.

EDIT: was forgetting about this: in the view render the EditorTemplate via

@Html.EditorFor (m => m.FirstAddress)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文