0
I am refactoring an ASP.NET MVC application written by another developer. My intention is to remove the use of FormCollection
.
Before the controller method signature was the following:
public ActionResult Salvar(FormCollection ParametroformCollection, FormCollection ParametroFormHidden, string ParametroView, string ParametroStrDirecao)
The forms were sent via ajax, using serializeArray()
So I created two models, one for each form, but in the controller the objects are not filled, being null. I tried to serialize with serializeArray()
and with serialize()
. I don’t know why it’s not working.
HTML of the Forms
<form id="hiddenForms" method="POST">
<input type="hidden" id="idhiddenFormPlaca" name="namehiddenFormPlaca" value="" />
<input type="hidden" id="idhiddenFormFabricante" name="namehiddenFormFabricante" value="" />
<input type="hidden" id="idhiddenFormAnoModelo" name="namehiddenFormAnoModelo" value="" />
<input type="hidden" id="idhiddenFormOficina" name="namehiddenFormOficina" value="" />
<input type="hidden" id="idhiddenFormCarrinho" name="namehiddenFormCarrinho" value="" />
<input type="hidden" id="idhiddenFormAlteracao" name="namehiddenFormAlteracao" value="" />
</form>
<form id="containerForm" method="POST">
<input type="text" id="idPlaca" name="namePlaca" value="@Model.strPlacaVeiculo" />
<div class="radio" style="display:none;">
<label><input type="radio" id="idRbCarros" name="optradio" value="Carros e Utilitários Pequenos">Carros</label>
</div>
<div class="radio" style="display:none;">
<label><input type="radio" id="idRbMotos" name="optradio" value="Motos">Motos</label>
</div>
<div class="radio" style="display:none;">
<label><input type="radio" id="idRbCaminhoes" name="optradio" value="Caminhões e Micro-Ônibus">Caminhões</label>
</div>
</form>
Javascript of sending
function enviar() {
var form = $("#containerForm").serialize();
var formhidden = $("#hiddenForms").serialize();
$.ajax({
type: "POST",
url: '@Url.Action("Salvar", "Home")',
data: { ParametroformCollection: form, ParametroFormHidden: formhidden, ParametroView: "Placa", ParametroStrDirecao: ParametroDirecao },
success: function (result) {
}
});
}
Controller
[HttpPost]
public ActionResult Salvar(PlacaForm ParametroformCollection, FormHidden ParametroFormHidden, string ParametroView, string ParametroStrDirecao)
{
....
}
Model
public class FormHidden
{
public string namehiddenFormPlaca { get; set; }
public string namehiddenFormFabricante { get; set; }
public string namehiddenFormAnoModelo { get; set; }
public string namehiddenFormOficina { get; set; }
public string namehiddenFormCarrinho { get; set; }
public string namehiddenFormAlteracao { get; set; }
}
public class PlacaForm
{
public string namePlaca { get; set; }
}
It didn’t work. Yet the models were null.
– user26552
@Murilo takes a look at your Javascript and compare! the code above is tested. look at the part
$.ajax
!– novic