当前位置: 动力学知识库 > 问答 > 编程问答 >

Dynamically building a viewmodel and applying UI validation,Asp.Net MVC 5

问题描述:

In my application,based on the selection of a field on the UI,I am loading a list of fields to be displayed from the database on the UI.Based on the selection,it is configured in the database each field is required or optional.After the UI is built,I do a post to the same view model(In the controller action).

What is the best way to do this?

I thought about doing this using reflection and add attributes on the properties based on the IsRequired flag against each field in the database,but i guess i have to eliminate the fields not needed from the UI.

So should i create a class as below as the best option or do i have something else?

Public Class ViewModelTicket

{

Public string EmailAddress{get;set}

Public bool IsRequired{get;set}

Public bool ShouldDisplay{get;set}

}

and throw a bunch of if else statements on the View ?

Thanks

网友答案:

I would go with what you started, but I would put it in a collection so that your model is a collection or has a collection of that class you started with. This way, you can easily expand your model to have more fields.

UPDATE I still think you could use the collection to eliminate the need for ShouldDisplay in your model, and your collection will simply contain fields you want to display or get input for.

Alternatively, you could put your ShouldDisplay value in the class of the containing div.

So you view would have something like this:

<div class="[email protected]">
     @Html.LabelFor(m => m.EmailAddress) 
     @Html.TextBoxFor(m => m.EmailAddress) 
</div>

Which would require this css:

.show-false { display: none; }

As for the IsRequired, you could use something like the RequiredIfTrue attribute in your model.

So your model would be:

Public Class ViewModelTicket
{
   [RequiredIfTrue(IsRequired)]
   Public string EmailAddress{get;set}
   Public bool IsRequired{get;set}
   Public bool ShouldDisplay{get;set}
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: