Submit form through ajax and callback an alert - c#

I submit a form using ajax request. The form is actually inside a modal popup. The submission works well. But I want it to show an alert that said the form is submitted and close the current modal. Here is my code:
$('#btnBookRoom').click(function() {
$.ajax({
url: "/Booking/BookRoom",
type: "POST",
data: $('#frmRoomBooking').serialize(),
datatype: "json",
sucess: function(data) {
alert('Room Booking Success');
$('#roomBookingModal').modal('hide');
}
});
});
Controller:
public ActionResult BookRoom(RoomBookingInputModel roomBooking)
{
var domain = new RoomBooking
{
GuestId = roomBooking.GuestId
};
db.RoomBookings.Add(domain);
db.SaveChanges();
return Json(domain, JsonRequestBehavior.AllowGet);
}
The alert doest shows and the modal also not hiding.

sucess isn't a valid callback in jQuery's ajax method. You need to change it to success.
Or better, use promise API to bind a success handler (as AJAX callbacks are already deprecated):
$.ajax({ ... })
.then(function() {
alert('Room Booking Success');
$('#roomBookingModal').modal('hide');
});

Related

Call action to render a partial View in a AjaxRequest

How you doing? I hope its good.
I have a "View" called Create and another two "partial" "views", a view is used to render a bootstrap modal and other to render a table, when I do a post in this modal I must to update that table, but when the model state of the modal is invalid I must call his action, how can I do this? I tryed to use return PartialView("ModalProduto", model);
try something like this
function () {
$.ajax({
url: URL/PartialViewAction,
type: 'GET',
data: $(form1.).serialize(), // or make your objects for the partial
success: function (data) {
$("#placeforthepartialview_as_a_modal").html(data);
},
error: function (e, data) {
}
});
});

mvc razor does not redirect to url after action

I want to open Edit page of a product but after Index action it does not redirect to that page from list page. Here you can find my codes:
On my List page:
function getProductDetail(id) {
$.ajax({
type: "POST",
url: '#Url.Action("Index","ProductDetail")',
dataType: "html",
data: JSON.stringify({ "productId": id }),
contentType: "application/json",
success: function (result) {
}
});
}
</script>
And on my ProductDetailController:
public ActionResult Index(int productId)
{
Product prod = GetProductDetail(productId);
return View(prod);
}
As per the comments above, you don't need to use AJAX at all in this situation. If you were planning to dynamically update the DOM, using an asynchronous call to the server, this would make sense. In your case, since you are just redirecting to the page, it would make more sense to use an actionlink and get rid of the AJAX call completely.
#HTML.ActionLink("Link Text","Index","ProductDetail",new {productId = "1234"}, null))

Redirect from partial view to view with json data object

I have a json data object which i need to pass from partial view to view with REDIRECT.
Lets say below is my partial view ( _createEmp.cshtml ):-
Note:- This partial view is in different view or page
<script type="text/javascript">
$(document).ready(function () {
LoadData();
});
function LoadData() {
$.ajax({
type: "GET",
url: baseURL + "Employee/GetEmpInfo",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
console.log(data);
**EmpData** = data; // EmpData object
},
error: function (error) {
console.log("Error: " + error);
}
});
}
</script>
<div>
<input type="submit" value="Save" onclick="SetEmpInfo()" />
</div>
And i want to transfer EmpData object to a different view (lets say NewEmp.cshtml), bind something in that view from passed "EmpData object" and open that view (or REDIRECT to view NewEmp.cshtml).
As you are using ajax, you could return the URL from your action and have it redirected in javascript.
Without seeing your controller action you would need to do something like this:
Controller
public ActionResult GetEmpInfo()
{
// Do stuff
return Json(new { success = true, redirecturl = Url.Action("GetEmpInfoSuccess") });
}
Then add something like this to your success handler in javascript:
Javascript (within your success handler)
success: function (data) {
if (data.success == true)
{
window.location = result.redirecturl;
}
}
Issuing a request to Employee/GetEmpInfo for getting the data and on success redirecting to other view - doesn't sound right
I think that you can do all this with one trip to server:
Write an Action that receives all the the parameters that GetEmpInfo receives. Lets call it NewEmployee.
If GetEmpInfo action is your code, reuse it's logic inside NewEmployee action to get EmpData. If it is not your code, you can use issue async request with HttpClient and get EmpData - All this performed on the server
Once you have EmpData you should have everything your need to return a NewEmp view.
In this particular case there is no need in AJAX at all. You can use regular form submit in case that you need to post some data or just a redirect to NewEmployee action.

Need to go Javascript Method before hit the MVC controller method

I have MVC project. I need to do client side validation on run time. When click the form submit button I need to hit JavaScript Method first and then it is return true move to Controller method.
Just Assume following code type:
JavaScript OnClick Method:
$(function () {
$('#btnSave').on('click', function (event) {
$.ajax({
url: '/Service/Utility/ThresholdValidation',
type: $("#addNewOrderForm").attr('method'),
data: $("#addNewOrderForm").serialize(),
success: function (data) {
if (data != "") {
event.preventDefault();
alert(data);
return false;
}
else {
return true;
}
}
});
});
});
Controller Method:
[HttpPost]
[BaseAuthenticationFilter(UserTypeEnum.Admin, PermissionEnum.CanSendRemittance)]
public ActionResult Create(Invoice model)
{
// Method Goes here
}
Here I cant popup validation alert message. When I click the button it will hit the Controller method. I need to go first javascript method and then if true go to controller method
Please help this.
Try following code, you have to return false in click handler directly instead of ajax response event. because ajax is asynchronous it will execute the ajax and call out from event handler immediately before getting the response of ajax.
So check if data not exists then submit the form otherwise show validation message
$('#btnSave').on('click', function (event) {
$.ajax({
url: '/Service/Utility/ThresholdValidation',
type: $("#addNewOrderForm").attr('method'),
data: $("#addNewOrderForm").serialize(),
success: function (data) {
if (data != "") {
alert(data);
}
else {
$("form").submit();
}
}
});
event.preventDefault();
return false;
});

How to use custom AuthorizeAttribute with AJAX

With help of fellow friends I managed to find a solution for my problem from this topic: Reusable way to allow an account to be used by a single person at a time
I have a SingleLogin class which inherits from AuthorizeAttribute and implements a custom AuthorizeCore method for the purpose of re-usability of my single-login code:
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool isAuthorized = base.AuthorizeCore(httpContext);
if (isAuthorized)
{
int userId = (int)WebSecurity.CurrentUserId;
using (var db = new UsersContext())
{
if ((httpContext.Session.SessionID != db.getSessionId(userId))
|| db.getSessionId(userId) == null)
{
WebSecurity.Logout();
isAuthorized = false;
httpContext.Response.Redirect("/Home/Index");
}
}
}
return isAuthorized;
}
Everything works fine except my JsonResult action:
[HttpPost]
public JsonResult MessageSave(string message)
{
bool messageSaved = false;
int userId = (int)WebSecurity.CurrentUserId;
message = HttpUtility.HtmlEncode(message);
// Model method - adding chat log - db
db.addChatLog(message, userId);
messageSaved = true;
return Json(new { messageSaved = messageSaved });
}
This method is triggered by Ajax POST call which you can see in code example below. Just basic POST.
EDIT 3
Please check these images: http://imgur.com/a/Cjael .. Hm I guess POST does trigger, but have no idea why does my alert not work when I try to test it before $.ajax ... As you can see in response I do get Home/Index page but I am not redirected to home/index immediately(text stays inside of textBox and page just waits..), I have to push enter one more time to be redirected.. Very strange.
EDIT2
Seems like I can't even access my jQuery even after I get logged out. I put some alerts inside of my .js file.
I have a separate .js file which is then put in my View as <script src="~/Scripts/custom/homeChat.js"></script> . I pass the Razor values from View into my JS file via HTML5 data-.
My textBox element #txtMsg, triggers my jQuery event, therefore when I am logged out it probably doesn't recognize my textBox element anymore, and doesn't trigger my jQuery event?
Element that triggers .js in view is:
#Html.TextBox("txtMsg")
JS:
$("#txtMsg").keypress(function (e) {
//when enter
if (e.which == 13) {
alert("ALERT DOESNT TRIGGER");
$.ajax({
type: "POST",
url: url,
data: JSON.stringify({ message: input }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.messageSaved) {
$("#txtMsg").val("");
}
else {
window.location.href = urlhome;
}
}
});
}
}
});
So if you can't even come into your event, how can you even know something went wrong? I have this ˙HandleUnauthorizedRequest but you are required that you can get into your jQuery event(in my case .keypress in the js code above) for this to work if I understand right.
EDIT: Additional explanation
So let me explain the scenario. If I login with my username "john" from Firefox and again with username "john" from chrome, next action I do in Firefox, it will log me out and redirect me to Home/Index, because someone else made a new login in Chrome.
That is ok. Since you are not logged in anymore, you get redirected normally to your Home/Index if your action is normal ActionResult and returns view.
The problem I have is, that I have some other functionality in the page, which uses Ajax POST, and since you are logged out you can't POST to that JsonResult action therefore you can't even receive callback of error, which redirects you to Home/Index. I put some alerts into my JS, but no alert triggers which is normal, because I am not allowed on that page anymore anyway. If I want that my onEnter textbox redirects me to Home/Index I have to press enter twice. Is that all that could be done?
I am interested in best approach for this AJAX problem. I don't know how I should call it, but as I read from my previous topic it is called "handling AJAX timeouts"?
Thank you very much.
You can handle errors on AJAX request this way
$.ajax({
type: "POST",
url: url,
data: JSON.stringify({ message: input }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.messageSaved) {
$("#txtMsg").val("");
}
else {
window.location.href = urlhome;
}
},
error: function(xhr, status, error) {
// TODO: may be check error or status or xhr.statusCode()
window.location.href = urlhome;
}
});
jQuery $.ajax() docs
If understand it correctly you want to handle the unauthorized ajax request.
In that case you can override the HandleUnauthorizedRequest method in your attribute:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
filterContext.Result = new JsonResult();
}
else
{
filterContext.Result = new HttpStatusCodeResult((int)HttpStatusCode.Forbidden);
}
}

Categories