1

Estou desenvolvendo uma pagina, para candidatos a vaga de trabalho possam entrar e preencher suas informações pessoais, uma dessas informações é a foto, que tem que ser obrigatória.

Então criei o seguinte model:

{
    .
    .
    [Display(Name = "SolidWorks")]
    public int infSolid { get; set; }
    [StringLength(500)]
    [Display(Name = "Outros")]
    public string infOutro { get; set; }
    [Required]
    public byte[] foto { get; set; }
    public int atualizar {get;set;}
    [StringLength(200)]
    [Required]
    [DataType(DataType.Date)]
    [Display(Name = "Emissão RG")]
    public string emissaoRg { get; set; }
}

Onde defini como [Required] a variavel foto, porem quando faço o metodo POST, é retornado que o model não é valido:

View:

 @using (Html.BeginForm("IndexRecru", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.id)
    @Html.HiddenFor(model => model.foto);

    <div class="jumbotron">
        <h2>Bem Vindo ao OneeWeb - Recrutamento</h2>
        <p>@Session["razao_social"]</p>
        <div class="posPerfil">
            @if (imagePath != "")
            {
                <img src="@imagePath" class="fotoPerfil" alt="Foto Perfil" title="Foto Perfil">
            }
            else
            {
                <img src="~/Imagens/fotoPerfil.png" class="fotoPerfil" alt="Foto Perfil" title="Foto Perfil">
            }

            @if (imagePath == "")
            {                   
                @Html.TextBoxFor(model => model.foto, new { type = "file", name = "foto", id = "foto", accept="image/jpeg" })
                <br />
                @Html.ValidationMessageFor(model => model.foto, "", new { @class = "text-danger" })
           }
        </div>
    </div>
}

Controller:

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult IndexRecru(HttpPostedFileBase foto, [Bind(Include = "id,nome,sobreNome,telefone,celular,sexo,recado,email,nascimento,idade,ultimoEmpregoNome,ultimoEmpregoSuperior,ultimoEmpregoTel,ultimoEmpregoRamal,ultimoEmpregoAdmissao,ultimoEmpregoDemissao,ultimoEmpregoCargo,ultimoEmpregoSalario,ultimoEmpregoFuncao,ultimoEmpregoMotivo,PenultimoEmpregoNome,PenultimoEmpregoSuperior,PenultimoEmpregoTel,PenultimoEmpregoRamal,PenultimoEmpregoAdmissao,PenultimoEmpregoDemissao,PenultimoEmpregoCargo,PenultimoEmpregoSalario,PenultimoEmpregoFuncao,PenultimoEmpregoMotivo,pertenceClube,passatempoFavorito,tipoResidencia,fumante,alergico,alergicoQual,cirurgia,cirurgiaQual,pressaoAlta,diabete,coluna,tendinite,paisPressaoAlta,paisDiabete,paisColuna,paisTendinite,indicaPessoaNome1,indicaPessoaTel1,indicaPessoaNome2,indicaPessoaTel2,obs,candidatoEng,candidatoComercial,candidatoCompras,candidatoProd,candidatoTI,candidatoRH,candidatoPCP,candidatoFinanceiro,candidatoQualidade,candidatoSGQ,candidatoMan,estadoCivil,nomeConj,idadeConj,temFilhos,qntFilhos,rg,cpf,ctps,serieCtps,cnh,categoria,disSM,nomeMae,idadeMae,trabalhaMae,profissaoMae,nomePai,idadePai,trabalhaPai,profissaoPai,endereco,numero,bairro,cidade,estado,cep,escolaridadeSup,escolaridadeSupSemestre,escolaridadeSupInstituicao,escolaridadeSupConclusao,escolaridadeMed,escolaridadeMedSemestre,escolaridadeMedInstituicao,escolaridadeMedConclusao,escolaridadeFund,escolaridadeFundSemestre,escolaridadeFundInstituicao,escolaridadeFundConclusao,idiomaIngles,idiomaEspanhol,idiomaAlemao,idiomaOutro,infAutoCad,infOffice,infSolid,infOutro,foto,atualizar,emissaoRg")] Models.Brayton.Recrutamento recrutamento)
    {
        Contextos.OneeWeb_BraytonContext db = new Contextos.OneeWeb_BraytonContext();

        if (foto != null)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                foto.InputStream.CopyTo(ms);
                byte[] array = ms.GetBuffer();

                recrutamento.foto = array;
            }
        }

        if (ModelState.IsValid)
        {
            recrutamento.atualizar = 1;

            db.Entry(recrutamento).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();

            if (Session.Keys.Count == 0)
                return RedirectToAction("Login", "Account");
            else
                return RedirectToAction("Conclusao", "Recrutamento");
        }
        else
        {
            if (Session.Keys.Count == 0)
                return RedirectToAction("Login", "Account");
            else
                return View(recrutamento);
        }
    }

Então gostaria de saber como faço para passar a fato escolhida para a variavel model?

1 Resposta 1

1

A sua view model não está recebendo um byte[] foto e sim um HttpPostedFileBase, você pode armaze-lá como está fazendo mas para a validação você precisa tirar o required do atributo foto e declarar o seu upload.

Na sua ViewModel

{
    //...
    [DataType(DataType.Upload)]
    [Required]
    HttpPostedFileBase FotoUpload { get; set; }

    public byte[] foto { get; set; }
    //...
}

Na sua View

@if (imagePath == "")
{                   
    @Html.TextBoxFor(model => model.foto, new { type = "file", name = "FotoUpload", id = "foto", accept="image/jpeg" })
    <br />
    @Html.ValidationMessageFor(model => model.FotoUpload, "", new { @class = "text-danger" })
}

Na sua Controller

public ActionResult IndexRecru(HttpPostedFileBase FotoUpload, [Bind(Include = "id,nome,...")] Models.Brayton.Recrutamento recrutamento)
{
    Contextos.OneeWeb_BraytonContext db = new Contextos.OneeWeb_BraytonContext();

    if (FotoUpload != null)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            FotoUpload.InputStream.CopyTo(ms);
            byte[] array = ms.GetBuffer();

            recrutamento.foto = array;
        }
    }
    //...
}

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .