Send to filled model controller

Asked

Viewed 943 times

0

I have on my main page two partial views, each with a specific view model associated, where all fields of the screen are mounted through Razor, as an example 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 he filled to the controller through an Ajax call, and the information is distributed in the two existing models on the page.

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

I’m trying to do it this way:

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, serialize and convert the contents of this form to Json

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

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

$.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);
}
  • How’s your controller? You could post how you’re calling the parties?

  • Randrade, I’ve added more information about how I’m doing. I wanted to know if there is a way to pass via ajax the filled model, no need to convert to Json before, since the way I am doing I can not automatically fill object inside objects.

2 answers

0

Douglas Fernandes,

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

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

I created a form (html.beginForm) on each snippet 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 internal class within my model view.

When performing the ajax call, the method in the controller expects to receive an object of type Acointernocadastroviewmodel, which is composed by:

 /* 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 call ajax, at the time of filling this object.

1) I am getting the data from 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 am 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 at the controller, some fields are not correctly filled.

The name of the fields after serialization is being composed by the name of the inner class + the name of the property, example: Information.Codidentaco.

I’m guessing that’s the problem... If you could remove the name of the internal class from the name, you could convert to Json and serialize again in the controller.

What better path do you suggest?

Thank you!

  • Now I understood better than you need, I thought you had an object formed by simple fields (string, int, etc). I will edit my answer to this case

  • I understood what is happening, so that the input name is correct you can not pass the template this way: @Html.Dropdownlistfor(model => model.Informacoes.Codidentaco..), create a partial view, and pass the model. Information for it, in the view you will render like this : @Html.Dropdownlistfor(model => model.CodIdentAco...), this will make the name correct.

0


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

View

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

On the controller

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

If for other reasons you cannot 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
 }
});

On the controller

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

EDITION 1

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

Ancient

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

New

var base = $("#frm-Detalhes-Acos-Internos").serializeArray();
base.push({ name: "NovoCampo", value:"Novo Valor" }); 
var data = $.param(base);
  • Got it... if I need to pass on other information on the "date" is it possible? In my case for example, I have an editable UI-grd angular on the screen and also need to send the user-filled information to the controller in the same method

  • In this case, you have to use serializeArray, and then $.param to format the data. I will edit my reply to put a better example.

  • In this case, the grid data is already in array format, but inside the object expected in the controller it is a typed list. There is the possibility to pass only this information through Json?

Browser other questions tagged

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