1
I need to do a post, and so far I’m trying to do by AJAX to send an object to the Controller, but I’m having trouble receiving the object.
View/html:
<select name="Servers" id="servers" multiple>
<option value='{ "Id": "1", "Site": "234", "Tecnologia" : "89" }'>Server 1</option>
<option value='{ "Id": "12", "Site": "21", "Tecnologia" : "12" }'>Server 2</option>
<option value='{ "Id": "45", "Site": "332", "Tecnologia" : "56" }'>Server 3</option>
</select>
Javascript/Jquery:
var servers = [];
$("#myForm select:selected").each(function(i){
servers.push(JSON.parse($(this).val()));
});
var model = {
"Nome": "qualquer nome aqui",
"Servers": servers
}
$.ajax({
type: "POST",
url: "/Home/Add",
data: model,
dataType: "json",
success: function (msg) {
//Qualquer código aqui
}
});
public class EmpresaModel
{
public string Nome { get;set; } // Nome está vindo preenchido
public List<ServerModel> Servers { get;set; } // Como faço para isso vir preenchido?
}
public class ServerModel
{
public string Id { get;set; }
public string Site { get;set; }
public string Tecnologia { get;set; }
}
My question would be how do I get this list of objects that I created via ajax by the model in the controller? The name is coming and filling in the model, but the list is not. Something like this:
[HttpPost]
public JsonResult Add(EmpresaModel model)
{
//codigo aqui
}
NOTE: Code made now only for example, may have typo or something like.
The problem is that your
EmpresaModel
expects an attribute calledServers
and you are sending a JSON withServidores
. Another detail that was not presented is the version of . Net MVC that you are using, if it is a recent add theFromBody
since it is aPOST
... ex.: public JsonresultAdd([FromBody]EmpresaModel model)
– Leandro Angelo