开发者

MVC validator for custom object

开发者 https://www.devze.com 2023-03-16 22:48 出处:网络
I have some model for my View and custom object as a property there, like this: class SomeModel { public object Data { get; set; }

I have some model for my View and custom object as a property there, like this:

class SomeModel {
  public object Data { get; set; }
}

and in View:

@model Blablabla.SomeModel

For example, in Model.Data I put some object with properties: Name, DateBirth and Amount. I'd like to create editors for these properties, like this:

@Html.EditorFor(m => m.Data.Name)
@Html.ValidateMessageFor(m => m.Data.Name)

But I cannot do this since m.Data is object, and compiler will not pass this. In case with EditorFor - I can replace it with my own <input type="..." ... /> without problems.

But I cannot find a way how to include MVC's Validator (from MicrosoftMvcValidation.js) to my input, and I don't want to create my own javascripts for all attributes from System.Compone开发者_JAVA技巧ntModel.DataAnnotations.

Is there a way to use MVC's Validator for my custom object without information about what properties it has (I'm generating editors by enumerating properties through the Reflection).

UPD: I cannot write just @Html.ValidateMessageFor(m => m.Data.Name) because I don't know about the property name before. I can do it only through the Reflection like this: @Html.ValidateMessageFor(m => m.Data.GetType().GetProperty(colName).GetValue(m.Data, null)), where colName contains the property name (Name, DateBirth or Amount).


I'm always hesitant to suggest use of the dynamic keyword however for what you're doing, this is at least one option.

By making your Data property of type dynamic you'll be able to set properties on it at runtime and also use it in your EditorFor.

public dynamic Data { get; set; }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号