Monorail - come chiamare il metodo lato server da jQuery
-
05-10-2019 - |
Domanda
Sto cercando di chiamare un'azione sul lato server in un controller da jQuery:
$.ajax({
url:'http://localhost:88/admin/business/11/GetChildBusinessTypes',
data: { parentId: $('#business_parentbusinesstype_id').val() },
dataType: 'json',
success: fillChildBusinessTypes,
error: ajaxError
});
Ecco l'azione di controllo:
public string GetChildBusinessTypes(int parentId)
{
//get child business types.
var businessTypes = BusinessTypeRepository.GetChildBusinessTypes(parentId);
//convert to JSON.
var serializer = new JavaScriptSerializer();
return serializer.Serialize(businessTypes);
}
E 'dandomi questo errore:
monorotaia non poteva risolvere un'istanza di vista del motore per il modello 'Admin \ Business \ GetChildBusinessTypes' Ci sono due possibili ragioni: o il modello non esiste, oppure il motore di visualizzazione che maniglie un'estensione di file specifico non è stato configurati correttamente web.config (sezione monorotaia, viewEngines nodo).
E 'chiaro che sta cercando di ottenere l'azione come se fosse una vista e erroring fuori. Ho provato a inviarlo come POST invece di una GET, ma ricevere la stessa rror. Che cosa devo fare per ottenere questo lavoro?
Grazie! Justin
Soluzione
Ecco la risposta per gli altri che stanno cercando di chiamare azioni di controllo da jQuery e ritorno JSON ...
Metodo di controllo:
[return: JSONReturnBinder(Properties = "Id,Name")]
public BusinessType[] GetChildBusinessTypes(int parentId)
{
var businessTypes = BusinessTypeRepository.GetChildBusinessTypes(parentId);
return businessTypes;
}
Javascript:
$(document).ready(function () {
$('#business_parentbusinesstype_id').change(function () {
jQuery.ajax({
url: "$UrlHelper.For("%{action='$business.site.id/GetChildBusinessTypes'}")",
data: { parentId: $('#business_parentbusinesstype_id').val() },
dataType: 'json',
type: 'GET',
success: fillChildBusinessTypes,
error: ajaxError
});
});
});
function fillChildBusinessTypes(json) {
//get business types.
var businessTypes = eval(json);
//bind business types to dropdown.
$("#business_businesstype_id").get(0).options.length = 0;
$("#business_businesstype_id").get(0).options[0] = new Option("Select a Business Type", "0");
jQuery.each(businessTypes, function(index, item) {
$('#business_businesstype_id').get(0).options[$("#business_businesstype_id").get(0).options.length] = new Option(item.Name, item.Id);
});
//show child dropdown.
Show($('#spnChildBusinessTypes'));
}