Send to driver model filled

0

I have on my main page two partial views, each with a specific view model associated, where all screen fields are assembled through Razor, as shown below:

<div class="row">
  <div class="col-sm-6 col-md-5 col-lg-4">
    <div class="form-group">
      <label>Área Cliente Aciaria</label>
      @Html.DropDownListFor(model => model.CodAreaProce, Model.ListaAreaProce, "", new { @id = "ddl-Cod-Area-Proce", @class = "form-control input-sm" })
    </div>
  </div>
  <div class="col-sm-4 col-md-3 col-lg-2">
    <div class="form-group">
      <label>Peso Específico</label>
      <div class="input-group">
        @Html.TextBoxFor(model => model.VlrPesoEspec, new { @id = "txt-Vlr-Peso-Espec", @class = "form-control input-sm", @maxlength = "5" })
        <span class="input-group-btn" style="width: 2px;"></span>
        @Html.DropDownListFor(model => model.CodUnidaMedid, Model.ListaUnidaMedid, "", new { @id = "ddl-Cod-Unida-Medid", @class = "form-control input-sm" })
      </div>
    </div>
  </div>
  <div class="col-sm-3 col-md-2 col-lg-1">
    <div class="form-group">
      <label>Diâmetro Ideal</label>
      @Html.TextBoxFor(model => model.VlrDiametroIdeal, new { @id = "txt-Vlr-Diametro-Ideal", @class = "form-control input-sm", @maxlength = "4" })
    </div>
  </div>
  <div class="col-sm-4 col-md-3 col-lg-2">
    <div class="checkbox checkbox-warning" style="margin-top: 25px; padding-left: 20px">
      @Html.CheckBoxFor(model => model.Transicao, new { @id = "chk-Transicao" })
      <label style="padding-left: 0px;">Aço de Transição</label>
    </div>
  </div>
</div>

When the user triggers the save event, I need to send all the data that is populated by it to the controller via an Ajax call, and the information is distributed in the two models on the page.

How can I send this filled object in the View to the controller?

I'm trying to do as follows:

1) I created a form within each partial view

@using (Html.BeginForm ("Save", "AcosInternos", FormMethod.Post, new {@id="frm-Details-Acos-Internos"))

2) Before the ajax call, I serialize and convert to Json the contents of this form

var json = JSON.stringify($('#frm-Detalhes-Acos-Internos').serializeObject());

3) Send via ajax the value obtained and in the controller convert Json to type viewmodel

$.ajax({
cache: false,
async: true,
type: "POST",
url: '/AcosInternos/Salvar',
dataType: "json",
data: {
   dados: json
}

4) In the controller, I get Json and perform the conversion

public ActionResult Salvar(string dados)
{
    AcoInternoViewModel acoInternoViewModel = this.DeserializarObjeto<AcoInternoViewModel>(dados);
}
    
asked by anonymous 02.09.2016 / 18:34

2 answers

0

You can use the native MVC Ajax.BeginForm to do the post in ajax.

View

@using (Ajax.BeginForm("Salvar", "AcosInternos", = new AjaxOptions( HttpMethod = "POST")))
{
//Renderizar campos
}

No controller

public ActionResult Salvar(AcoInternoViewModel dados)
{
//Código
}

If for other reasons you can not use the native structure, simply change your code to:

Javascript:

$.ajax({
 cache: false,
 async: true,
 type: "POST",
 url: '/AcosInternos/Salvar',
 data: $("#frm-Detalhes-Acos-Internos").serialize(),
 success: function (data) {
    //seu código
 }
});

No controller

public ActionResult Salvar(AcoInternoViewModel dados)
{
//Código
}

EDITION 1

For additional fields and pass in the correct format, you will need to change the serialization code.

Old

$("#frm-Detalhes-Acos-Internos").serialize()

New

var base = $("#frm-Detalhes-Acos-Internos").serializeArray();
base.push({ name: "NovoCampo", value:"Novo Valor" }); 
var data = $.param(base);
    
02.09.2016 / 19:48
0

Douglas Fernandes,

I'm making such a mess ... see if you can help me.

I have two partial views where the registration information is divided.

I created a form (html.beginForm) in each section to group the data according to its type, for example:

@using (Html.BeginForm("Salvar", "AcosInternos", FormMethod.Post, new { @id = "frm-Acos-Internos-Edicao-Dados"}))
            {
<div class="row">
  <div class="col-sm-4 col-md-3 col-lg-2">
    <div class="form-group">
      <label>Código Aço</label>
      <div class="input-group" style="width:100%">
        @Html.DropDownListFor(model => model.Informacoes.CodIdentAco, Model.Informacoes.ListaSubgrupoAco, "", new { @id = "ddl-SubGrupo-Aco", @class = "form-control input-sm" })
        <span class="input-group-btn" style="width: 2px;"></span>
        @Html.TextBoxFor(model => model.Informacoes.CodAcoNumero, new { @id = "txt-Codigo-Aco", @class = "form-control input-sm", @maxlength = "3", @style = "width: 50px" })
      </div>
    </div>
  </div>
  <div class="col-sm-4 col-md-3 col-lg-2">
    <div class="form-group">
      <label>Norma/Descrição Comercial</label>
      <div class="input-group">
        @Html.TextBoxFor(model => model.Informacoes.CodIdentNorma, new { @id = "txt-Cod-Ident-Norma", @class = "form-control input-sm", @maxlength = "4" })
        <span class="input-group-btn" style="width: 2px;"></span>
        @Html.TextBoxFor(model => model.Informacoes.NomIdentAco, new { @id = "txt-Nom-Ident-Aco", @class = "form-control input-sm", @maxlength = "16" })
      </div>
    </div>
  </div>
  <div class="col-sm-4 col-md-3 col-lg-2">
    <div class="form-group">
      <label>Norma/Descrição Corporativa</label>
      <div class="input-group">
        @Html.TextBoxFor(model => model.Informacoes.CodIdentMarca, new { @id = "txt-Cod-Ident-Marca", @class = "form-control input-sm", @maxlength = "4" })
        <span class="input-group-btn" style="width: 2px;"></span>
        @Html.TextBoxFor(model => model.Informacoes.NomIdentMarca, new { @id = "Nom-Ident-Marca", @class = "form-control input-sm", @maxlength = "16" })
      </div>
    </div>
  </div>
  <div class="col-sm-6 col-md-5 col-lg-4">
    <div class="form-group">
      <label>Situação</label>
      <div class="radio">
        <label class="radio-inline">@Html.RadioButtonFor(x => x.Informacoes.Situacao, "A", new {@id="opt-Situacao-Ativo", @checked = true})Ativo</label>
        <label class="radio-inline">@Html.RadioButtonFor(x => x.Informacoes.Situacao, "I", new {@id="opt-Situacao-Inativo"})Inativo</label>
        <label class="radio-inline">@Html.RadioButtonFor(x => x.Informacoes.Situacao, "E", new {@id="opt-Situacao-Experiencia"})Experiência</label>
        <label class="radio-inline">@Html.RadioButtonFor(x => x.Informacoes.Situacao, "P", new {@id="opt-Situacao-Pendente"})Pendente</label>
      </div>
    </div>
  </div>
</div>
<div class="row">
  <div class="col-sm-4 col-md-3 col-lg-2">
    <div class="form-group">
      <label>Temperaturas Lingotamento</label>
      <div class="input-group">
        @Html.TextBoxFor(model => model.Informacoes.TempLingotamento, new { @id = "txt-Vlr-Temp-Lingotamento", @class = "form-control input-sm", @maxlength = "4" })
        <span class="input-group-btn" style="width: 2px;"></span>
        @Html.TextBoxFor(model => model.Informacoes.TempLingotamento2, new { @id = "txt-Vlr-Temp-Lingotamento2", @class = "form-control input-sm", @maxlength = "4" })
      </div>
    </div>
  </div>
  <div class="col-sm-4 col-md-3 col-lg-2">
    <div class="form-group">
      <label>Padrão</label>
      @Html.TextBoxFor(model => model.Informacoes.Padrao, new { @id = "txt-Padrao", @class = "form-control input-sm", @maxlength = "4" })
    </div>
  </div>
  <div class="col-sm-6 col-md-6 col-lg-6">
    <div class="form-group">
      <label>Config. Norma Corporativa</label>
      <div class="radio">
        <label class="radio-inline">@Html.RadioButtonFor(x => x.Informacoes.ConfigNormaCorporativa, "1", new {@id="opt-Norma-Regra-Geral"})1 - Imprimir Via Regra Geral</label>
        <label class="radio-inline">@Html.RadioButtonFor(x => x.Informacoes.ConfigNormaCorporativa, "2", new {@id="opt-Norma-Aco-Externo"})2 - Imprimir Via Aço Externo</label>
        <label class="radio-inline">@Html.RadioButtonFor(x => x.Informacoes.ConfigNormaCorporativa, "3", new {@id="opt-Norma-Nao-Imprimir", @checked = true})3 - Não Imprimir</label>
      </div>
    </div>
  </div>
</div>
}

This example information is related to the main information, which is an inner class within my view model.

At the time of the ajax call, the method in the controller expects to receive an object of type AcoInternoCadastroViewModel, which is composed of:

 /* Dados primários */
 public InformacoesAco Informacoes { get; set; }

 /* Dados Gerais */
 public DetalhesAco Detalhes { get; set; }

 /* Classificações */
 public Classificacao Classificacao { get; set; }

My problem is in the ajax call, when filling this object.

1) I'm getting the data for each form:

 var formDados = $('#frm-Acos-Internos-Edicao-Dados');
var formDadosGerais = $('#frm-Acos-Internos-Edicao-DadosGerais :not([name="search_listbox"])');
var formClassificacao = $('#frm-Acos-Internos-Edicao-Classificacao').not(':input[type=hidden]');

2) In the ajax call, I'm trying to pass the information in N ways:

$.ajax({
cache: false,
async: true,
type: "POST",
url: '/AcosInternos/Salvar',
dataType: "json",

//data: JSON.stringify({ Informacoes: formDados.serialize(), Detalhes: formDadosGerais.serialize(), Classificacao: formClassificacao.serialize() }),
//data: $.param({ Informacoes: formDados.serializeArray(), Detalhes: formDadosGerais.serialize(), Classificacao: formClassificacao.serialize() }),
//data: JSON.stringify({ Informacoes: formDados.serializeObject(), Detalhes: formDadosGerais.serializeObject(), Classificacao: formClassificacao.serializeObject() }),

But when it arrives in the controller, some fields are not filled correctly.

The name of the fields after the serialization is composed of the name of the inner class + the name of the property, for example: Information.CodIdentAco.

I'm wondering if this is the problem ... If I could remove the inner class name from the name, I could convert it to Json and serialize it back to the controller.

What best way do you suggest?

Thank you!

    
05.09.2016 / 14:32