attribute passing empty in Entity

Asked

Viewed 47 times

0

I am trying to do an update only that the fields of Issue Date and Due Date do not have the slightest idea why, is passing null when I call the save changes button.

Inside the controller comes a saying that the mission date can not be null.

@model PortalAdmCC.Models.FaturaInterna

@{
    ViewBag.Title = "Editar";
}
<h2><span class="glyphicon glyphicon-edit"></span> @ViewBag.Title Fatura Interna</h2>
<hr />
<h3>Confirma a edição dessa Fatura Interna?</h3>


@using (Html.BeginForm("Edit", "FaturaInternas", FormMethod.Post, new { id = "formCrud" }))
{
    @Html.AntiForgeryToken()

<div class="form-horizontal">

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

    <div class="form-group">
        <label for="Descricao" class="control-label col-md-2">Descrição</label>
        <div class="col-md-10">
            @Html.EditorFor(model => model.Descricao, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Descricao, "", new { @class = "text-danger" })
        </div>
    </div>


    <div class="form-group">
        <label for="DtEmissao" class="control-label col-md-2">Data de Emissão</label>
        <div class="col-md-10">
            @Html.EditorFor(model => model.DtEmissao.Date, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.DtEmissao.Date, "", new { @class = "text-danger" })
        </div>
    </div>





    <div class="form-group">
        <label for="FoneAcc" class="control-label col-md-2">Descrição</label>
        <div class="col-md-10">
            @Html.EditorFor(model => model.FoneAcc, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.FoneAcc, "", new { @class = "text-danger" })
        </div>
    </div>



    <div class="form-group">
        <label for="NFFat" class="control-label col-md-2">Número da NF e/ou Fatura</label>
        <div class="col-md-10">
            @Html.EditorFor(model => model.NFFat, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.NFFat, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <label for="MesRef" class="control-label col-md-2">Mês de Referencia</label>
        <div class="col-md-10">
            @Html.EditorFor(model => model.MesRef, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.MesRef, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <label for="DtVenc" class="control-label col-md-2">Data de Vencimento</label>
        <div class="col-md-10">
            @Html.EditorFor(model => model.DtVenc.Date, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.DtVenc, "", new { @class = "text-danger" })
        </div>
    </div>


    <div class="form-group">
        <label for="Val" class="control-label col-md-2">Valor Total</label>
        <div class="col-md-10">
            @Html.EditorFor(model => model.ValorT, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.ValorT, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <label for="Val" class="control-label col-md-2">Valor do Item</label>
        <div class="col-md-10">
            @Html.EditorFor(model => model.ValorI, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.ValorI, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-md-2" for="AreaReclamacaoId">Area de Reclamaçao</label>
        <div class="col-md-10">
            @Html.DropDownList("AreaReclamacaoId", null, new { htmlAttributes = new { @class = "form-control" } })

            @Html.ValidationMessageFor(model => model.AreaReclamacaoId)
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-2" for="FornecedorId">Fornecedor</label>
        <div class="col-md-10">
            @Html.DropDownList("FornecedorId", null, new { htmlAttributes = new { @class = "form-control" } })

            @Html.ValidationMessageFor(model => model.FornecedorId)
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-2" for="ObjetoCustoId">Objeto de Custo</label>
        <div class="col-md-10">
            @Html.DropDownList("ObjetoCustoId", null, new { htmlAttributes = new { @class = "form-control" } })

            @Html.ValidationMessageFor(model => model.ObjetoCustoId)
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-2" for="CentroCustoId">Centro de Custo</label>
        <div class="col-md-10">
            @Html.DropDownList("CentroCustoId", null, new { htmlAttributes = new { @class = "form-control" } })

            @Html.ValidationMessageFor(model => model.CentroCustoId)
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-2" for="FormaPagamentoId">Forma de Pagamento</label>
        <div class="col-md-10">
            @Html.DropDownList("FormaPagamentoId", null, new { htmlAttributes = new { @class = "form-control" } })

            @Html.ValidationMessageFor(model => model.FormaPagamentoId)
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-2" for="ChaveLancamentoId">Chave de Lançamento</label>
        <div class="col-md-10">
            @Html.DropDownList("ChaveLancamentoId", null, new { htmlAttributes = new { @class = "form-control" } })

            @Html.ValidationMessageFor(model => model.ChaveLancamentoId)
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-2" for="ContaContabilId">Conta Contabil</label>
        <div class="col-md-10">
            @Html.DropDownList("ContaContabilId", null, new { htmlAttributes = new { @class = "form-control" } })

            @Html.ValidationMessageFor(model => model.ContaContabilId)
        </div>
    </div>

    @*<div class="form-group">
            <label class="control-label col-md-2" for="ProtocoloId">Protocolo</label>
            <div class="col-md-10">
                @Html.DropDownList("ProtocoloId", null, new { htmlAttributes = new { @class = "form-control" } })

                @Html.ValidationMessageFor(model => model.ProtocoloId)
            </div>
        </div>*@


    <div class="form-actions no-color">
        <input type="button" value="Confirmar" class="btn btn-warning" />
    </div>
</div>
}



@Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/projeto/EnviarFormulario.js"></script>

<script type="text/javascript">

    var btnAcao = $("input[type='button']");
    var formulario = $("#formCrud");

</script>

my controller

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Services;
using System.Web.Services;
using PortalAdmCC.AcessoDados;
using PortalAdmCC.Models;
using PortalAdmCC.ViewModels;

namespace PortalAdmCC.Controllers
{
    public class FaturaInternasController : Controller
    {
         private ApplicationDbContext db = new ApplicationDbContext();

        // GET: FaturaInternas
        [HttpGet]
        public ActionResult Index()
        {
            return View(db.FaturaInternas.ToList());
        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = true)]
        public JsonResult GetAreaReclamacao()
        {
            var areasReclamacao = db.AreaReclamacaos.Select(areaReclamacao => new { areaReclamacao.Id, areaReclamacao.Descricao});
            return Json(areasReclamacao, JsonRequestBehavior.AllowGet);
        }
        [WebMethod]
        [ScriptMethod(UseHttpGet = true)]
        public JsonResult GetFornecedor()
        {
            var fornecedores = db.Fornecedores.Select(fornecedor => new { fornecedor.Id, fornecedor.Nome }).Take(10000);
            return Json(fornecedores, JsonRequestBehavior.AllowGet);
        }

        //public JsonResult
        //função que trás todos os centros de custo
        [WebMethod]
        [ScriptMethod(UseHttpGet = true)]
        public JsonResult GetCentroCusto()
        {
            var centroCustos = db.CentroCustos.Select(centroCusto => new { centroCusto.Id, centroCusto.Descricao });
            return Json(centroCustos, JsonRequestBehavior.AllowGet);
        }


        //função que trás todos os objetos de custo
        [WebMethod]
        [ScriptMethod(UseHttpGet = true)]
        public JsonResult GetObjetoCusto()
        {
            long centroCusto = 0;
            if (Request.QueryString["centroCusto"] != "")
            {
                centroCusto = long.Parse(Request.QueryString["objetoCusto"]);
            }

            var objetosCusto = db.ObjetoCustos.Where(d => d.CentroCustoId == centroCusto.ToString())
                .Select(objetoCusto => new
                {
                    objetoCusto.Id,
                    objetoCusto.Descricao
                });

            return Json(objetosCusto, JsonRequestBehavior.AllowGet);
        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = true)]
        public JsonResult GetFormaPagamento()
        {
            var formasPagamento = db.FormaPagamentos.Select(formaPagamento => new { formaPagamento.Id, formaPagamento.Descricao });
            return Json(formasPagamento, JsonRequestBehavior.AllowGet);
        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = true)]
        public JsonResult GetChaveLancamento()
        {
            var chavesLancamento = db.ChaveLancamentos.Select(chaveLancamento => new { chaveLancamento.Id, chaveLancamento.Descricao });
            return Json(chavesLancamento, JsonRequestBehavior.AllowGet);
        }


        [WebMethod]
        [ScriptMethod(UseHttpGet = true)]
        public JsonResult GetTipoDoc()
        {
            var tiposDocumento = db.TipoDoc.Select(tipoDocumento => new { tipoDocumento.Id, tipoDocumento.Descricao });
            return Json(tiposDocumento, JsonRequestBehavior.AllowGet);
        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = true)]
        public JsonResult GetContaContabil()
        {
            var contasContabeis = db.ContasContabeis.Select(contaContabil => new { contaContabil.Id, contaContabil.Descricao });
            return Json(contasContabeis, JsonRequestBehavior.AllowGet);
        }


        [WebMethod]
        [ScriptMethod(UseHttpGet = true)]
        public JsonResult GetProtocolo()
        {
            var protocolos = db.Protocolos.Select(protocolo => new { protocolo.Id, protocolo.Descricao });
            return Json(protocolos, JsonRequestBehavior.AllowGet);
        }

        public JsonResult Listar(ParametrosPaginacao parametrosPaginacao)
        {
            DadosFiltrados dadosFiltrados = FiltrarEPaginar(parametrosPaginacao);

            return Json(dadosFiltrados, JsonRequestBehavior.AllowGet);
        }

        private DadosFiltrados FiltrarEPaginar(ParametrosPaginacao parametrosPaginacao)
        {
            //  var areaClientes = db.AreaClientes.Include(a => a.GAreaCliente);
            var faturaInternas = db.FaturaInternas.AsQueryable();

            int total = faturaInternas.Count();

            if (!String.IsNullOrWhiteSpace(parametrosPaginacao.SearchPhrase))
            {
                //  areaClientes = areaClientes.Where("Area.Contains(@0) OR DescricaoGAreaCliente(@0)", parametrosPaginacao.SearchPhrase);
                faturaInternas = faturaInternas.Where("Descricao.Contains(@0)", parametrosPaginacao.SearchPhrase);
            }

            var FaturaInternaPagina = faturaInternas.OrderBy(parametrosPaginacao.CampoOrdenado).Skip((parametrosPaginacao.Current - 1) * parametrosPaginacao.RowCount).Take(parametrosPaginacao.RowCount);

            DadosFiltrados dadosFiltrados = new DadosFiltrados(parametrosPaginacao)
            {
                rows = FaturaInternaPagina.ToList(),
                total = total
            };
            return dadosFiltrados;
        }
        // GET: FaturaInternas/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            FaturaInterna faturaInterna = db.FaturaInternas.Find(id);
            if (faturaInterna == null)
            {
                return HttpNotFound();
            }
            return PartialView(faturaInterna);
        }

        // GET: FaturaInternas/Create
        public ActionResult Create()
        {

            return PartialView();
        }

        // POST: AreaClientes/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Create(FaturaInterna faturaInterna) //[Bind(Include = "Id,Area,GAreaClienteId")]
        {
            if (ModelState.IsValid)
            {
                db.FaturaInternas.Add(faturaInterna);
                db.SaveChanges();
                return Json(new { resultado = true, mensagem = "Fatura Interna cadastrado com sucesso" });
            }
            else
            {
                IEnumerable<ModelError> erros = ModelState.Values.SelectMany(item => item.Errors);

                return Json(new { resultado = false, mensagem = erros });

            }
        }

        private void PopulaAreaReclamacao(object selecionaArea = null)
        {
            var areaReclamacao = from d in db.AreaReclamacaos
                                 orderby d.Descricao
                                 select d;
            ViewBag.AreaReclamacaoId = new SelectList(areaReclamacao, "Id", "Descricao", selecionaArea);
        }

        private void PopulaFornecedor(object selecionaFornecedor = null)
        {
            var fornecedor = from d in db.Fornecedores
                                 orderby d.Nome
                                 select d;
            ViewBag.FornecedorId = new SelectList(fornecedor, "Id", "Nome", selecionaFornecedor);
        }

        private void PopulaObjetoCusto(object selecionaObjetoCusto = null)
        {
            var objetocCusto = from d in db.ObjetoCustos
                             orderby d.Descricao
                             select d;
            ViewBag.ObjetoCustoId = new SelectList(objetocCusto, "Id", "Descricao", selecionaObjetoCusto);
        }


        private void PopulaCentroCusto(object selecionaCentroCusto = null)
        {
            var centroCusto = from d in db.CentroCustos
                             orderby d.Descricao
                             select d;
            ViewBag.CentroCustoId = new SelectList(centroCusto, "Id", "Descricao", selecionaCentroCusto);
        }


        private void PopulaFormaPagamento(object selecionaFormaPagamento = null)
        {
            var formaPagamento = from d in db.FormaPagamentos
                               orderby d.Descricao
                               select d;
            ViewBag.FormaPagamentoId = new SelectList(formaPagamento, "Id", "Descricao", selecionaFormaPagamento);
        }

        private void PopulaChaveLancamento(object selecionaChaveLancamento = null)
        {
            var chaveLancamento = from d in db.ChaveLancamentos
                                 orderby d.Descricao
                                 select d;
            ViewBag.ChaveLancamentoId = new SelectList(chaveLancamento, "Id", "Descricao", selecionaChaveLancamento);
        }

        private void PopulaContaContabil(object selecionaContaContabil = null)
        {
            var contaContabil = from d in db.ContasContabeis
                                  orderby d.Descricao
                                  select d;
            ViewBag.ContaContabilId = new SelectList(contaContabil, "Id", "Descricao", selecionaContaContabil);
        }

        private void PopulaProtocolo(object selecionaProtocolo = null)
        {
            var protocolo = from d in db.Protocolos
                                orderby d.Descricao
                                select d;
            ViewBag.ContaContabilId = new SelectList(protocolo, "Id", "Descricao", selecionaProtocolo);
        }



        // GET: FaturaInternas/Edit/5
        // GET: AreaClientes/Edit/5
        public ActionResult Edit(int? id)
        {

            if (id == null)
            {

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }


            FaturaInterna faturaInterna = db.FaturaInternas.Find(id);
            if (faturaInterna == null)
            {
                return HttpNotFound();
            }


            PopulaAreaReclamacao(faturaInterna.Id);
            PopulaFornecedor(faturaInterna.Id);
            PopulaObjetoCusto(faturaInterna.Id);
            PopulaCentroCusto(faturaInterna.Id);
            PopulaFormaPagamento(faturaInterna.Id);
            PopulaChaveLancamento(faturaInterna.Id);
            PopulaContaContabil(faturaInterna.Id);
            PopulaProtocolo(faturaInterna.Id);

            // ViewBag.GAreaClienteId = new SelectList(db.GAreaClientes, "Id", "Descricao", areaCliente.GAreaClienteId);
            return PartialView(faturaInterna);
        }

        // POST: AreaClientes/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Edit(FaturaInterna faturaInterna) //[Bind(Include = "Id,Area,GAreaClienteId")] 
        {
            if (ModelState.IsValid)
            {

                db.Entry(faturaInterna).State = EntityState.Modified;
                db.SaveChanges();

                return Json(new { resultado = true, mensagem = "Fatura Interna editado com sucesso" });
            }
            else
            {
                IEnumerable<ModelError> erros = ModelState.Values.SelectMany(item => item.Errors);

                return Json(new { resultado = false, mensagem = erros });
            }
        }

        // GET: AreaClientes/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            FaturaInterna faturaInterna = db.FaturaInternas.Find(id);
            // AreaCliente areaCliente = db.AreaClientes.Include(areaCliente => areaCliente.GAreaCliente).FirstOrDefault(a => a.GAreaClienteId == id);

            if (faturaInterna == null)
            {
                return HttpNotFound();
            }
            return PartialView(faturaInterna);
        }

        // POST: AreaClientes/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {

            try
            {
                FaturaInterna faturaInterna = db.FaturaInternas.Find(id);
                db.FaturaInternas.Remove(faturaInterna);
                db.SaveChanges();

                return Json(new { resultado = true, mensagem = "Fatura Interna excluída com sucesso" });
            }
            catch (Exception ex)
            {
                return Json(new { resultado = false, mensagem = ex.Message });

            }


        }


        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
  • do not post all your code, only the relevant parts to the question

  • your EnviarFormulario.js is including these fields?

  • Yes, I found the solution, I forced the field that is giving error in the format I needed

1 answer

1


I found the solution.

Inside the controller, I forced the code to pass date in the format I needed.

[HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Edit(FaturaInterna faturaInterna) //[Bind(Include = "Id,Area,GAreaClienteId")] 
        {
            if (ModelState.IsValid)
            {
                string dtVencimento = faturaInterna.DtVencimento.ToString("dd/MM/yyyy");

                faturaInterna.DtVencimento = DateTime.Parse(dtVencimento);
                db.Entry(faturaInterna).State = EntityState.Modified;
                db.SaveChanges();

                return Json(new { resultado = true, mensagem = "Fatura Interna editado com sucesso" });
            }
            else
            {
                IEnumerable<ModelError> erros = ModelState.Values.SelectMany(item => item.Errors);

                return Json(new { resultado = false, mensagem = erros });
            }
        }

Browser other questions tagged

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