Conditional Display Elements Using Razor

Is there a smarter way to show / hide elements conditionally (with a razor) than this below? The view is very large and the service bothers me:

@if(@Model.Atendimento.PrazosEEntregas.Visivel) { <div> <h4>Prazos e entrega do serviço</h4> @if (!string.IsNullOrWhiteSpace(@Model.Atendimento.PrazosEEntregas.PrazoFinalizacaoServico)) { <p>@Model.Atendimento.PrazosEEntregas.PrazoFinalizacaoServico</p> } @if (!string.IsNullOrWhiteSpace(@Model.Atendimento.PrazosEEntregas.PrazoRetiradaDocumento)) { <p><strong>Prazo de retirar o documento:</strong> @Model.Atendimento.PrazosEEntregas.PrazoRetiradaDocumento</p> } @if (!string.IsNullOrWhiteSpace(@Model.Atendimento.PrazosEEntregas.OndeRetirarServico)) { <p><strong>Onde retirar/receber:</strong> @Model.Atendimento.PrazosEEntregas.OndeRetirarServico</p> } @if (!string.IsNullOrWhiteSpace(@Model.Atendimento.PrazosEEntregas.ObservacaoPrazoRetirada)) { <p><strong>Observação:</strong> @Model.Atendimento.PrazosEEntregas.ObservacaoPrazoRetirada</p> } </div> } 

Thanks Hoisel

+6
source share
3 answers

You can write a user assistant that will conditionally display the contents:

 public static class HtmlExtensions { public static IHtmlString FormatValue( this HtmlHelper htmlHelper, string value, string label ) { if (string.IsNullOrWhiteSpace(value)) { return MvcHtmlString.Empty; } var result = string.Format( "<p><strong>{0}</strong> {1}</p>", htmlHelper.Encode(label), htmlHelper.Encode(value) ); return new HtmlString(value); } } 

and then:

 @Html.FormatValue( Model.Atendimento.PrazosEEntregas.ObservacaoPrazoRetirada, "Observação:" ) 

Another possibility is to use a display template:

 @Html.DisplayFor(x => x.Atendimento.PrazosEEntregas.ObservacaoPrazoRetirada) 

Then you can define a display pattern for the string type (or custom):

 @model string @if (!string.IsNullOrWhiteSpace(Model)) { <p> <strong>@ViewData.ModelMetadata.DisplayName</strong> @ViewData.TemplateInfo.FormattedModelValue </p> } 

and on your view model:

 [DisplayName("Observação:")] [UIHint("MyTemplate")] public string ObservacaoPrazoRetirada { get; set; } 
+7
source

You can reassign the code in your view by refactoring some code as follows:

 <h4>Prazos e entrega do serviço</h4> @{ PrazosEEntregas prazosEEntregas = Model.Atendimento.PrazosEEntregas; } @if (!string.IsNullOrWhiteSpace(prazosEEntregas.PrazoFinalizacaoServico)) { <p>prazosEEntregas.PrazoFinalizacaoServico</p> } @if (!string.IsNullOrWhiteSpace(prazosEEntregas.PrazoRetiradaDocumento)) { //etc. } 

I already guessed the type of prazosEEntregas in your code, you may need to replace it with the correct type.

+2
source

It is not a representation task to handle model logic. Move this logic to the appropriate controller.

Things to keep in mind if your presentation starts to be too big, start making partial views. Perhaps some code can be reused.

0
source

Source: https://habr.com/ru/post/904169/


All Articles