Reputation: 1071
when I create a area I use JQuery to call the action create the action save to the db and return jsaon now when is save i want to be rendered to my index view how can i do that?? whith my code i have is that posible? i tried to call to the action index with jquery it call fine to the action but not render to the view index
[HttpPost]
public ActionResult Create(int? id,string nombre, int idDpto )
{
try
{
if (id != null)
{
Area c = (from x in db.Areas
where x.AreaId == id
select x).First();
c.NombreArea = nombre;
c.DepartamentoId = idDpto;
db.SaveChanges();
return Json(new { ok = true, message = "saved employee " });
}
Area e = new Area()
{
NombreArea = nombre,
DepartamentoId = idDpto
};
db.Areas.Add(e);
db.SaveChanges();
return Json(new { ok = true, message = "saved employee " });//+ emp.NameEmployee
}
catch (Exception ex)
{
return Json(new { ok = false, message = ex.Message });
}
}
function saveEmployee() {
var urlSave = '@Url.Action("Create")';
var iddpt = $("#cmbDept").val();
var name = $("#txtemp").val();
var idArea = $("#AreaId").val();
if (!name) {
window.alert('el nombre y el departamento son requeridos');
}
else {
if (! iddpt) {
window.alert('el departamento es requerido');
}
else {
$.ajax({
type: "POST",
url: urlSave,
data: { id: idArea, nombre: name, idDpto: iddpt },
success: function (returndata) {
if (returndata.ok) {
window.alert(' Guardado ');
}
else {
window.alert(' error : ' + returndata.message);
}
}
}
);
}
}
}
Upvotes: 1
Views: 1350
Reputation: 218808
The fundamental issue here is the difference between an AJAX call from within JavaScript and a regular web request. From the server's perspective, there isn't much of a difference. It's just how the browser handles those.
Your Create
action is set up to be used by an AJAX call, which you're doing. That's all well and good. But I assume that Index
is not. That one expects to be a regular request. As I said, from the server's perspective, there really isn't a difference. So, as you've observed, the call to Index
happens just fine. It just doesn't "render" in the browser.
The terminology is a little mixed up here. You don't want to "render the view with jQuery," you want to direct the browser to make that request. When should this happen? I'm assuming that you want this redirect to take place perhaps after the success
in your AJAX call?
If you want your JavaScript to redirect, then you're on the right track. Just approach it differently. jQuery doesn't call the Index
view in an AJAX manner (because it wouldn't know what to do with the response). Simply use a JavaScript call to redirect the user to another resource:
window.location.href = "http://yourserver/controller/action/etc";
Upvotes: 4