Working on MVC 3 application with some CRUD operations with jQuery ajax.
I post my user detail form to controller method to Save the information.
Once the information get saved, i am redirecting to Detail page by passing saved id and some tempdata information to show some message like ‘User saved successfull’
But it is not at going to Detail method in controller, after SaveUserDetail method.
Here is my controller code
[HttpPost, Authorize]
public ActionResult UserDetail(string Id)
{
User user = AdminService.SelectUserByUserName(Id);
UserDetailViewModel viewModel = Mapper.Map<User, UserDetailViewModel>(user);
if (TempData["SaveStatus"] != null && TempData["SaveStatus"] == "true")
{
viewModel.InSaveMode = true;
viewModel.SaveStatus = true;
}
return View(viewModel);
}
[HttpPost, Authorize, ValidateAntiForgeryToken]
public ActionResult SaveUserDetail(UserDetailViewModel viewModel)
{
User userToSave = new User();
AdminService.UpdateUser(userToSave);
TempData["SaveStatus"] = "true";
return RedirectToAction("UserDetail", new { Id = viewModel.userId});
}
My jQuery code
$("#user-detail-form").submit(function (e) {
if ($(this).valid()) {
$.post('@Url.Action("SaveUserDetail")',
$(this).serialize(), function (data) {
$("#user-detail-box").html(data);
$.validator.unobtrusive.parse($("#user-detail-box"));
});
}
e.preventDefault();
});
Get rid of the
[HttpPost]attribute from yourUserDetailmethod if you intend to redirect to it.If a controller action is decorated with the
[HttpPost]attribute this means that this action is accessible only with the POST HTTP verb. But in your case you are redirecting to it (return RedirectToAction("UserDetail", new { Id = viewModel.userId});) and as you know a redirect in HTTP means 302 status code with aLocationheader followed by a GET request by the client to the target location.If you had used FireBug or a similar javascript debugging tool in your browser to analyze the AJAX request you would have immediately seen this.