Form losing model list

Asked

Viewed 98 times

3

I have the following models:

Models

public class Atividade : BaseEntity
{
    public virtual int Id{ get; set; }
    public virtual string Descricao{ get; set; }
    public virtual IList<Anotacao> Anotacoes{ get; set; }
}

public class Anotacao : BaseEntity
{
    public virtual int Id{ get; set; }
    public virtual Atividade Atividade{ get; set; }
    public virtual string Motivo{ get; set; }
}

The problem is when I’m changing my activity my Notes list is lost every time I save. how can I solve this problem?

View

@model SPACE.Model.Atividade
@using (Html.BeginForm("SalvarAtividade", "Atividade", FormMethod.Post, new { id = "formAtividade" }))
                {
                    @Html.AntiForgeryToken()

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

                        <div class="form-group">
                            @Html.LabelFor(model => model.Descricao, htmlAttributes: new { @class = "control-label" })
                            @Html.EditorFor(model => model.Descricao, new { htmlAttributes = new { @class = "form-control", @required = "required" } })
                            <small>@Html.ValidationMessageFor(model => model.Descricao, "", new { @class = "text-danger" })</small>
                        </div>

                    <hr />

                    <div class="form-actions" align="right">
                            <a href="@Url.Action("GridAtividade", "Atividade", new { Area = "Cadastro" })" class="btn btn-danger waves-effect waves-light">
                                <i class="fa fa-times" aria-hidden="true"></i>
                            </a>

                        <button type="button" id="btn-salvar-atividade" title="Sem permissão de usuário." class="btn btn-success" onclick="validaDataHora();"> <i class="fa fa-check"></i> Salvar</button>
                    </div>
                }

Scripts

    $("#btn-salvar-atividade").click(function () {
        debugger;
        var formAtividade = $("#formAtividade").serialize();

        $.ajax({
            type: "POST",
            //contentType: "application/json",
            url: "@Url.Action("SalvarAtividade", "Atividade", new { area = "Cadastro" })",
            data: JSON.stringify({
                model: formAtividade
            }),
            success: function (data) {
                return msg("Salvo com sucesso");
            }
        });

    });

</script>

Controller

public async Task<ActionResult> SalvarAtividade(Atividade model)
{
      using (var save = _session.BeginTransaction())
        {
            try
            {
                _session.SaveOrUpdate(model);

                save.Commit();

                return new RetornoSalvarDto { Model = model, ERetornoCrud = ERetornoCrud.Sucesso };
            }
            catch (Exception e)
            {
                save.Rollback(); 
                _session.Clear();

                string error = "Ops! Ocorreu um problema ao tentar salvar." + e.Message;

                return new RetornoSalvarDto { Model = model, ERetornoCrud = ERetornoCrud.Erro };
            }
        }
}
  • Could you describe further details of your saving method? Probably Voce is saving an object that is not tied to his session and with that he removes all the joins with the activities that were before.

  • Updated with my save method... However, when the parameter arrives, it is enough to save with the zeroed list...

  • Post details of Retornosalvardto also

1 answer

1


I can point out two situations here.

1) When you submit FORM, it sends out all values that are in components within it, such as what you did with the item:

@Html.HiddenFor(model => model.Id)

That when this is rendered in HTML, a:

<input type="hidden" name="Id" value="?" />

If you want the list values to be sent back in the FORM commit, just put their values in Hiddenfields with the correct names.

2) Entityframework will override the interconnected objects if you change the values. If in your case this is not necessary, that is, if these values never need to be changed, just configure your Entityframework to not change the related table objects.

NOTE: In my opinion, the way you save the data in the database is a little strange. The most correct (in my opinion) is that first you refer to the object to be changed, change only the different values in it, and save the object you have just consulted. Avoid persisting objects that have just come from your FORM, just to be safe.

OBS²: I ended up speaking Entityframework and then I saw that it was Nhibernate. But the idea is the same...

Browser other questions tagged

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