MVC3 动态 DataAnnotation 属性 StringLength
更新#3:整个问题
我有一个HB类:
public class HB
{
public int Id { get; set; }
[StringLength(3000)]
public string Text { get; set; }
public Title Title { get; set; }
}
和标题:
public class Title
{
public int Id { get; set; }
public string Name { get; set; }
public int MaxChar { get; set; }
}
在你写HB(这是一篇文章)之前,你必须选择你的标题,所以你的HB的StringLength。文本可以确定。这意味着,这篇文章只能有一定数量的字符,具体取决于作者的“标题”。示例:Title1 只能写入 1000 个字符的“HB”,Title2 可以写入 3000 个字符的“HB”。所以。这意味着 StringLength
必须来自 Title.MaxChar
。最聪明的方法是什么?
Title 实体是将存储在数据库中的前缀数据。
说得非常清楚,我想要实现的目标是: [StringLength(Title.MaxChar)]
我已经在 Webforms 中为这种机制完成了一百万次结构/设计,我的大脑就是无法适应 mvc,所以一些帮助将不胜感激。代码将更加感激。
UPDATE #3: Entire question
I have a class HB:
public class HB
{
public int Id { get; set; }
[StringLength(3000)]
public string Text { get; set; }
public Title Title { get; set; }
}
And Title:
public class Title
{
public int Id { get; set; }
public string Name { get; set; }
public int MaxChar { get; set; }
}
Before you can write a HB (which is kind of an article), you have to choose your title, so your StringLength for HB.Text can be determined. Meaning, this article can only have a certain amount of chars, deppending on what 'Title' the writer has. Example: Title1 can only write a 'HB' with 1000 chars, and Title2 can write a 'HB' with 3000 chars. So. Thats means the the StringLength
has to come from Title.MaxChar
. Whats the smartest way to do that?
The Title entity is prefixed data that will be stored in the db.
To be crystal clear, what I want to achieve is something in the line with: [StringLength(Title.MaxChar)]
Ive done structure/design for this mechanism in Webforms a million times, my brain just cant addapt to mvc, so some help would be appreciated. Code would be even more appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
很确定这是不可能的。在我看来,这是试图将业务逻辑强制纳入属于控制器的模型中。
在这种情况下,我将在 Text 属性
[StringLength(3000)]
上创建该属性。在控制器中,在验证期间,我会写一些类似的内容:我相信这将完成您想要做的事情。现在,对于 Title 对象,我会在您的模型中将其展平一点:
这是假设您需要在视图中显示该信息。如果您只需要引用它来进行业务逻辑验证,只需拥有
TitleId
属性,并在需要时使用它在控制器中实例化Title
对象。如果这些属性不可编辑,请不要忘记为它们创建隐藏输入!Pretty sure that is not possible as written. This strikes me as trying to force business logic into the model that belongs in the controller.
In this situation, I would make the attribute on the Text property
[StringLength(3000)]
. In the controller, during validation, I would write something along these lines:I believe this will accomplish what you are trying to do. Now, for the Title object, I'd flatten that out a bit in your model:
This is assuming you need to display that information in your view. If you just need to reference it for your business logic validation, just have the
TitleId
property and use that to instantiate theTitle
object in your controller when you need it. Don't forget to make hidden inputs for each of these properties if they are not editable!