After a validation I call the controller in the action (Add) to add a new record through javascript.
If the insertion succeeds I give RedirectToAction
to the index of this same controller passing the id of the profile that I just registered, however nothing happens!
JavaScript:
function validaFormulario() {
var formularioValidado = false;
formularioValidado = validaFormulario();
if (formularioValidado) {
var perfil = obtemPerfilDoFormulario();
$.ajax({
type: 'POST',
url: '/Perfil/Adiciona',
data: {
"perfil": perfil
},
async: false,
error: function (xhr, status, error) {
alert(error);
}
});
}
}
Controller:
public ActionResult Adiciona(Perfil perfil)
{
PerfilDAO perfilDAO = new PerfilDAO();
perfil.UsuarioId = usuario.Id;
perfilDAO.Adiciona(perfil);
EnviaEmailRecebimentoCadastro(perfil.Email);
EnviaEmailAtivacaoDeConta(perfil.Email);
return RedirectToAction("Index", "Perfil", perfil.Id);
}
I was able to get around the problem by sending the profile id by Json and manually doing the redirect by adding the javascript "success" return.
Would this approach be correct? I am starting in web development and wanted guidance on these "good practices". After all,% w / w of my controller should work. Where did I make the mistake?
Code with problem bypassed:
Controller sending Json:
public ActionResult Adiciona(Perfil perfil)
{
//restante do codigo
return Json(perfil.Id);
}
Javascript with success:
$.ajax({
type: 'POST',
url: '/Perfil/Adiciona',
data: {
"perfil": perfil
},
async: false,
success: function (data) {
var id = JSON.parse(data);
window.location.href = "/Usuario/Lista/" + id;
},
error: function (xhr, status, error) {
alert(error);
}