How to pass an Enum type parameter together with the Model for a Partialview - Asp.net Core MVC

Asked

Viewed 81 times

1

I’m having a hard time passing an Enum parameter to a Partialview using Viewdata. It is giving conversion error (in Partialview), because the received type seems to be string or other type and is different from Enum. Someone knows how to help me?

Call from the Partialview:

@await Html.PartialAsync("~/Views/Pessoa/_PessoaGenerico.cshtml", Model, new ViewDataDictionary(ViewData){ { "pessoaTipo", PessoaTipo.Filial } })

Receiving the parameter in Partialview:

@model Retaguarda.Application.ViewModels.Pessoa.PessoaGenericoViewModel
@{
    PessoaTipo pessoaTipoRecebido = this.ViewData.ContainsKey("pessoaTipo") ? this.ViewData["pessoaTipo"] : PessoaTipo.Filial; //Caso não receba o valor do parametro será setado para Filial. 
}

Enum:

public enum PessoaTipo
{
    [Description("PESSOA")]
    Pessoa = 1,
    [Description("FILIAL")]
    Filial = 2,
    [Description("USUÁRIO")]
    usuario = 3,
    [Description("CLIENTE")]
    Cliente = 4,
    [Description("FORNECEDOR")]
    Fornecedor = 5,
    [Description("FUNCIONARIO")]
    Funcionario = 6
}
  • 1

    It seems to me necessary to be done the cast, something like that PessoaTipo pessoaTipoRecebido = this.ViewData.ContainsKey("pessoaTipo") ? (Models.PessoaTipo)this.ViewData["pessoaTipo"] : PessoaTipo.Filial; Where Models is the namespace.

  • It worked!!! Thank you @Barbetta :)

1 answer

2


It is necessary that the cast of ViewData because he doesn’t know that inside it contains a PessoaTipo.

Your line of code should be like this:

PessoaTipo pessoaTipoRecebido = this.ViewData.ContainsKey("pessoaTipo") ? (Models.PessoaTipo)this.ViewData["pessoaTipo"] : PessoaTipo.Filial;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.