嵌套与所需属性可选模型属性 [英] Optional model property with nested required properties
问题描述
使用code这样的:
公共类FooModel { 公共BarModel酒吧{搞定;组; }}公共类BarModel { [需要]
公共字符串巴兹{搞定;组; }}
我想渲染 FooModel.Bar
的形式,但有它是可选的。但是,窗体不会没有在文本框中输入任何提交 BarModel.Baz
。有没有办法去做出一个关于 FooModel
嵌套模式可选,无需删除 RequiredAttribute标签
?
有没有一种方法去使嵌套模型FooModel
可选,而无需去除RequiredAttribute标签?
块引用>这并不是说我知道。我建议你使用,这将适应您观的要求视图模型(即有
巴兹
属性可选):公共类FooModel
{
公共BarViewModelModel酒吧{搞定;组; }
}公共类BarViewModelModel
{
公共字符串巴兹{搞定;组; }
}这就是为什么你应该总是使用视图模型,从来没有通过你的域模型的意见的原因之一。正如你可以看到你的域模型不适应的意见的具体要求。你可以有某些观点必需和可选的其他意见的一些属性。
With code like the following:
public class FooModel { public BarModel Bar { get; set; } } public class BarModel { [Required] public string Baz { get; set; } }
I want to render
FooModel.Bar
in a form, but have it be optional. However, the form won't submit without any input in the text box forBarModel.Baz
. Is there a way to go about making the nested model inFooModel
optional without having to remove theRequiredAttribute
?解决方案Is there a way to go about making the nested model in FooModel optional without having to remove the RequiredAttribute?
Not that I am aware of. I would recommend you using a view model which will be adapted to the requirements of your view (i.e. have the
Baz
property optional):public class FooModel { public BarViewModelModel Bar { get; set; } } public class BarViewModelModel { public string Baz { get; set; } }
That's one of the reasons why you should always use view models and never pass your domain models to the views. As you can see your domain models are not adapted to the specific requirements of the views. You could have some properties required in certain views and optional in other views.
这篇关于嵌套与所需属性可选模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!