Is there a smarter way to show/hide elements conditionally (with razor) than this below? The view is very large and I'm concerned about maintenance:
@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
You could write a custom helper that will conditionally output 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 could define a display template for the string type (or a custom one):
@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; }
You could redude the code in you View by refactoring some of the code like so:
<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 have guessed at the type of prazosEEntregas
in your code, you might need to replace that with the correct type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With