cw_dev
cw_dev

Reputation: 465

MVC 3 - Only display/use certain model properties

Being fairly new to MVC 3 I am not sure of the best approach for this. Let's say I have a simple class like this...

Public Class PDetail

    <Required>
    Public Property FirstName As String

    <Required>
    Public Property LastName As String

    <Required>
    Public Property CellNo As String

    <Required>
    Public Property PassportNo As String

    <Required>
    Public Property Nationality As String

    Public Property ExtraRequirements As String

End Class

This is used to create my model. During a booking process I may prompt for these values on a view. However depending on the type of booking I may not wish to ask some of these questions. For example I may not require the PassportNo and Nationality if the booking does not involve going to a foreign country.

What's the best way to deal with this? The easy way seems to be to have a separate property that determines which fields are shown as EditorFor and the others use HiddenFor. But is this sensible? Also when it comes to server side validation the hidden fields are still validated.

The class above is a simplified version of what I actually do. I have up to 10 fields that can be shown or hidden independently depending on the type of booking, so creating a separate model for each combination would be a nightmare.

Upvotes: 1

Views: 288

Answers (3)

Mike Simmons
Mike Simmons

Reputation: 1298

Steve Sanderson posted a good way to only validate incoming values, although you still need to validate the model, in your domain, as a whole to protect against malicious attacks.

You would need to protect yourself from the mass assignment attack, using the principles described here (using the Bind attribute for your case).

Upvotes: 1

Marc
Marc

Reputation: 6771

You can check the validations depending on your booking with implementing the IValidatableObject interface.

Read this post for more information.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039528

You may take a look at FluentValidation.NET which has a great integration with ASP.NET MVC and makes such validation scenarios very easy. It uses an imperative approach compared to the declarative approach used by Data Annotations which, as you described it, could be a nightmare.

Upvotes: 0

Related Questions