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);
}