1

In my model class I have a boolean property DoNotEmail.

In the UI design I've been given to create a view for, the meaning of the checkbox is inverted; i.e. the label next to the checkbox says "Send Email".

Normally I would add the checkbox like this: @Html.CheckBoxFor(model => model.DoNotEmail) but clearly this is the wrong way round.

Do I need to create a separate view model with a custom property for this checkbox, or is there some clever way I can do something like: @Html.CheckBoxFor(model => !model.DoNotEmail) (which clearly doesn't work)?

2
  • Is DoNotEmail a field from the database? Is your model class an entity or a custom model? Commented Jul 12, 2012 at 11:46
  • Yes it's a column in the database and yes the model class is an entity. Commented Jul 12, 2012 at 11:52

2 Answers 2

3

Passing entities directly to your view is never a good idea, if your DB schema ever changes you would have to go through all your views and update them. I would recommend creating a ViewModel and passing only the data required for the view, then map your DoNotEmail property in the controller. That way you maintain the abstraction between your model/view and keeps your view simple e.g.

public void ViewModel
{
    [DisplayName("Send Email")]
    public bool SendEmailNotification { get; set; }
}

View

@model ViewModel

@Html.CheckBoxFor(m => m.SendEmailNotifications)

Controller

public void Post(ViewModel model)
{
    var entity = ...;
    entity.DoNotEmail = !model.SendEmailNotification;
}
Sign up to request clarification or add additional context in comments.

3 Comments

+1 Thanks - I'd been only using ViewModels where I had to. Looks like I should be using them all the time then...
@Andy I would always recommend a view model, gives you a clean separation. If you find yourself needing to create view models in a lot of places have a look at AutoMapper
Thanks @James. AutoMapper looks useful.
3

Simplest way to do it which may be called a work around is that :

Make DontEmail a Hidden value. And create a Checkbox. Bind jquery event to it and when selected then invert the value of DontEmail. I hope i dont need to put in code to explain this. If required let me know.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.