1

I am finding that my UI code is looking rather messy, because I am having to add .Net formatting code, to my View code. An example:

<tr data-url="@Url.Action("EditTransaction", "Transaction", new {[email protected]})" class="clickableRow @(line.IsDeposit ? "credit_colour" : "") ">

So, the row needs to use the 'credit_colour' class if line.IsDeposit - else, the default TR class.

I have more of those, some more complex.

The main issue, in the above code, is the:

@(line.IsDeposit ? "credit_colour" : "")

Is it acceptable/good practise, to be using such formatting conditions within my view code, or should this sort of logic be performed within the Controller method, and somehow passed to the View?

1 Answer 1

2

It's a good practice to have all the logic separated from view. With that approach you'll be able to test your logic. And views are not testable.

I usually pass a viewmodel to the view with existing properties. In your case it should be something like LineClass. So you'll have:

<tag class="@LineClass">...</tag>

What is your view model? Do you use the model from your context (SQL/entity framework) in your views? If so, you should consider using Automapper to map those models to view models.

If you have client-side JavaScript framework, you can handle it there. In KnockoutJS you can create custom bindings, in Angular you can use directives.

Sign up to request clarification or add additional context in comments.

2 Comments

My View Models are different from the models from Entity Framework. They get translated into DTOs in the data layer, passed up to the controller, and then translated into MVC View Models in the controller. The models currently only hold data properties, things like, 'IsDeposit' which is used as shown above.
@Craig glad to hear that. I just think you have to add additional property to these models as I described above. If you have client-side JavaScript framework, you can handle it there. In KnockoutJS you can create custom bindings, in Angular you can use directives.

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.