Modelsatate.Isvalid always false

Asked

Viewed 247 times

0

When trying to save my model in the database, when trying to validate Modelstate.Isvalid, it is always false as if it had fields pending. I know that it is due to the Dropdownlist that returns me a string in fields that are objects. What is the best way to bind this data in a way that Modelstate recognizes?

I have the following model:

public class Requisicao
{
    public Guid RequisicaoId { get; set; }

    public int Numero { get; set; }
    [Required]
    public Porto Porto { get; set; }
    [Required]
    public Operador Operador { get; set; }
    [Required]
    public DateTime DataOperacao { get; set; }
    [Required]
    public Periodo Periodo { get; set; }
    public string Viagem { get; set; }
    [Required]
    public Navio Navio { get; set; }
    [Required]
    public LocalAtracacao LocalAtracacao { get; set; }
}

My controller:

public ActionResult Create()
    {
        ViewBag.Porto = new SelectList(portoDAO.Listar(), "PortoId", "Descricao");
        ViewBag.Periodo = new SelectList(periodoDAO.Listar(), "PeriodoId", "Descricao");
        ViewBag.Operador = new SelectList(operadorDAO.Listar(), "OperadorId", "NomeFantasia");
        ViewBag.Navio = new SelectList(navioDAO.Listar(), "NavioId", "Descricao");
        ViewBag.LocalAtracacao = new SelectList(localAtracacaoDAO.Listar(), "LocalAtracacaoId", "Descricao");
        return View();
    }

    // POST: Requisicoes/Create
    // Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para 
    // obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Numero,DataOperacao,Viagem")] Requisicao requisicao, FormCollection form)
    {
        var porto = int.Parse(form["Porto"]);
        var periodo = int.Parse(form["Porto"]);
        var operador = int.Parse(form["Operador"]);
        var navio = Guid.Parse(form["Navio"]);
        var localAtracacao = int.Parse(form["LocalAtracacao"]);
        if (porto > 0)
        {
            requisicao.Porto = portoDAO.Listar().Single(p => p.PortoId == porto);
        }
        if (periodo > 0)
        {
            requisicao.Periodo = periodoDAO.Listar().Single(p => p.PeriodoId == periodo);
        }
        if (operador > 0)
        {
            requisicao.Operador = operadorDAO.Listar().Single(o => o.OperadorId == operador);
        }
        if (navio != Guid.Empty)
        {
            requisicao.Navio = navioDAO.Listar().Single(n => n.NavioId == navio);
        }
        if (localAtracacao > 0)
        {
            requisicao.LocalAtracacao = localAtracacaoDAO.Listar().Single(la => la.LocalAtracacaoId == localAtracacao);
        }
        if (!ModelState.IsValid)
        {
            var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.ErrorMessage));
            // Breakpoint, Log or examine the list with Exceptions.
        }
        else if (ModelState.IsValid)
        {
            requisicao.RequisicaoId = Guid.NewGuid();
            requisicaoDAO.Criar(requisicao);
            return RedirectToAction("Index");
        }
        return View(requisicao);

and my view:

@model GestaoDeEscala.MVC.Models.Entidades.Requisicao

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Requisicao</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Numero, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Numero, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Numero, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.DataOperacao, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.DataOperacao, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.DataOperacao, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Viagem, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Viagem, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Viagem, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group row">
        @Html.LabelFor(model => model.Porto, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.DropDownList("Porto", (IEnumerable<SelectListItem>)ViewBag.Porto, String.Empty, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group row">
        @Html.LabelFor(model => model.Periodo, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.DropDownList("Periodo", (IEnumerable<SelectListItem>)ViewBag.Periodo, String.Empty, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group row">
        @Html.LabelFor(model => model.Operador, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.DropDownList("Operador", (IEnumerable<SelectListItem>)ViewBag.Operador, String.Empty, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group row">
        @Html.LabelFor(model => model.Navio, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.DropDownList("Navio", (IEnumerable<SelectListItem>)ViewBag.Navio, String.Empty, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group row">
        @Html.LabelFor(model => model.LocalAtracacao, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.DropDownList("LocalAtracacao", (IEnumerable<SelectListItem>)ViewBag.LocalAtracacao, String.Empty, new { @class = "form-control" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
  • This is the error that occurs when I try to save: The item Viewdata that has the key 'Port' is of the type 'Gestaodeescala.MVC.Models.Entidades.Porto', but it needs to be of the type 'Ienumerable<Selectlistitem>'.

  • Accessing ModelState in the debug you will find the Values which contains the errors, you will find some property with Errors > 0 then see what is.

  • I would use something like: https://gist.github.com/paulodiogo/d0f5b425085dea8878fdb5380222586e. you’re depending on the object directly. See if this way improves.

No answers

Browser other questions tagged

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