How to redirect to Login page from an Ajax postback? - ajax

I work on an MVC 3 application. My cshtml page looks like this:
#Ajax.BeginForm("Filter", new AjaxOptions() { UpdateTargetId = "div_GridPlaceholder")
{
...some HTML
<input id="btn_Filter" type='submit' ... />
}
<div id="div_GridPlaceholder">...</div>
The Filter ( ) action method marked with the Authorize attribute returns some string at the moment. Everything works fine but when the forms authentication ticket expires and I hit the btn_Filter button, my Login page gets rendered in the div_GridPlaceholder which is pretty strange. I would like to have the see the Login page rendered on the whole page instead of inside that div.
Any help is appreciated.

In your Logon action you could append a custom response HTTP header:
public ActionResult LogOn()
{
Response.AppendHeader("X-LOGON", "true");
return View();
}
and then subscribe for the complete event and test for the presence of this header and act accordingly:
$(function () {
$('#div_GridPlaceholder').ajaxComplete(function (event, XMLHttpRequest, ajaxOptions) {
if (XMLHttpRequest.getResponseHeader('X-LOGON') == 'true') {
window.location.href = '#Url.Action("LogOn", "Account")';
}
});
});

Related

Calling multiple action methods (using ajax) and showing the result of last in a new tab

I have a form in which I need to call two action methods, one after the other. This is how the flow goes.
First I check if the prerequisite data is entered by the user. If not then I show a message that user needs to enter the data first.
If all the prerequisite data is entered, I call an action method which return data. If there is no data returned then I show a message "No data found" on the same page.
If data is returned then I call another action method present in a different controller, which returns a view with all the data, in a new tab.
The View:
#using (Ajax.BeginForm("Index", "OrderListItems", null, new AjaxOptions { OnBegin = "verifyRequiredData"}, new { #id = "formCreateOrderListReport", #target = "_blank" }))
{
//Contains controls and a button
}
The Script in this View:
function verifyRequiredData() {
if ($("#dtScheduledDate").val() == "") {
$('#dvValidationSummary').html("");
var errorMessage = "";
errorMessage = "<span>Please correct the following errors:</span><ul>";
errorMessage += "<li>Please enter Scheduled date</li>";
$('#dvValidationSummary').append(errorMessage);
$('#dvValidationSummary').removeClass('validation-summary-valid').addClass('validation-summary-errors');
return false;
}
else {
$('#dvValidationSummary').addClass('validation-summary-valid').removeClass('validation-summary-errors');
$('#dvValidationSummary').html("");
$.ajax({
type: "GET",
url: '#Url.Action("GetOrderListReport", "OrderList")',
data: {
ScheduledDate: $("#dtScheduledDate").val(),
Crews: $('#selAddCrewMembers').val(),
Priorities: $('#selPriority').val(),
ServiceTypes: $('#selServiceTypes').val(),
IsMeterInfoRequired: $('#chkPrintMeterInfo').val()
},
cache: false,
success: function (data) {
debugger;
if (data !== "No data found") {
//var newUrl = '#Url.Action("Index", "OrderListItems")';
//window.open(newUrl, '_blank');
return true;
} else {
//Show message "No data found"
return false;
}
}
});
return false;
}
}
The "GetOrderListReport" Action method in "OrderList" Controller:
public ActionResult GetOrderListReport(OrderListModel model)
{
var contract = new OrderReportDrilldownParamDataContract
{
ScheduledDate = model.ScheduledDate
//Setting other properties as well
};
var result = OrderDataModel.GetOrderList(contract);
if (string.IsNullOrWhiteSpace(result) || string.IsNullOrEmpty(result))
{
return Json("No data found", JsonRequestBehavior.AllowGet);
}
var deserializedData = SO.Core.ExtensionMethods.DeserializeObjectFromJson<OrderReportDrilldownDataContract>(result);
// send it to index method for list
TempData["DataContract"] = deserializedData;
return Json(deserializedData, JsonRequestBehavior.AllowGet);
}
The last action method present in OrderListItems Controller, the result of which needs to be shown in a new tab:
public ActionResult Index()
{
var deserializedData = TempData["DataContract"] as OrderReportDrilldownDataContract;
var model = new OrderListItemViewModel(deserializedData);
return View(model);
}
The problem is that I am not seeing this data in a new tab, although I have used #target = "_blank" in the Ajax.BeginForm. I have also tried to use window.open(newUrl, '_blank') as can be seen above. But still the result is not shown in a new tab.
Please assist as to where I am going wrong?
If you are using the Ajax.BeginForm you shouldn't also be doing an ajax post, as the unobtrusive ajax library will automatically perform an ajax post when submitting the form.
Also, if you use a view model with data annotation validations and client unobtrusive validations, then there would be no need for you to manually validate the data in the begin ajax callback as the form won't be submitted if any validation errors are found.
The only javascript code you need to add in this scenario is a piece of code for the ajax success callback. That will look as the one you currently have, but you need to take into account that opening in new tabs depends on the browser and user settings. It may even be considered as a pop-up by the browser and blocked, requiring the user intervention to allow them as in IE8. You can give it a try on this fiddle.
So this would be your model:
public class OrderListModel
{
[Required]
public DateTime ScheduledDate { get; set; }
//the other properties of the OrderListModel
}
The form will be posted using unobtrusive Ajax to the GetOrderListReport of the OrderList controller. On the sucess callback you will check for the response and when it is different from "No data found", you will then manually open the OrderListItems page on a new tab.
This would be your view:
#model someNamespace.OrderListModel
<script type="text/javascript">
function ViewOrderListItems(data){
debugger;
if (data !== "No data found") {
var newUrl = '#Url.Action("Index", "OrderListItems")';
//this will work or not depending on browser and user settings.
//passing _newtab may work in Firefox too.
window.open(newUrl, '_blank');
} else {
//Show message "No data found" somewhere in the current page
}
}
</script>
#using (Ajax.BeginForm("GetOrderListReport", "OrderList", null,
new AjaxOptions { OnSucces= "ViewOrderListItems"},
new { #id = "formCreateOrderListReport" }))
{
#Html.ValidationSummary(false)
//input and submit buttons
//for inputs, make sure to use the helpers like #Html.TextBoxFor(), #Html.CheckBoxFor(), etc
//so the unobtrusive validation attributes are added to your input elements.
//You may consider using #Html.ValidationMessageFor() so error messages are displayed next to the inputs instead in the validation summary
//Example:
<div>
#Html.LabelFor(m => m.ScheduledDate)
</div>
<div>
#Html.TextBoxFor(m => m.ScheduledDate, new {id = "dtScheduledDate"})
#Html.ValidationMessageFor(m => m.ScheduledDate)
</div>
<input type="submit" value="Get Report" />
}
With this in place, you should be able to post the data in the initial page using ajax. Then based on the response received you will open another window\tab (as mentioned, depending on browser and user settings this may be opened in a new window or even be blocked) with the second page content (OrderListItems).
Here's a skeleton of what I think you are trying to do. Note that window.open is a popup though and most user will have popups blocked.
<form id="formCreateOrderListReport">
<input type="text" vaule="testing" name="id" id="id"/>
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
$('#formCreateOrderListReport').on('submit', function (event) {
$.ajax({
type: "POST",
url: '/home/test',
data: { id: $('#id').val()},
cache: false
}).done(function () {
debugger;
alert("success");
var newUrl = '/home/contact';
window.open(newUrl, '_blank');
}).fail(function () {
debugger;
alert("error");
});
return false;
});
</script>
Scale down the app to get the UI flow that you want then work with data.

Avoiding Duplicate form submission in Asp.net MVC by clicking submit twice

I am rendering a form in Asp.net MVC with a submit button. The page redirects after successful record addition into the database. Following is the code :-
[HttpPost]
public ActionResult Create(BrandPicView brandPic)
{
if (ModelState.IsValid)
{
if (!String.IsNullOrEmpty(brandPic.Picture.PictureUrl))
{
Picture picture = new Picture();
picture.PictureUrl = brandPic.Picture.PictureUrl;
db.Pictures.Add(picture);
brandPic.Brand.PictureId = picture.Id;
}
db.Brands.Add(brandPic.Brand);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
But, while testing, I saw that if the form is clicked again and again, the multiple entries are submitted and saved into the database.
How can i make sure that if the form has been submitted once to the server, then no duplicates are submitted.
I don't think this is quite a duplicate of the answer referenced in the comment, since the link is for spring MVC, and this question is for .NET MVC.
I actually spent a few hours on this a while back, and came up with the following. This javascript hooks nicely with the unobtrusive jquery validation, and you can apply it to any form that has <input type="submit". Note that it uses jquery 1.7's on function:
$(document).on('invalid-form.validate', 'form', function () {
var button = $(this).find(':submit');
setTimeout(function () {
button.removeAttr('disabled');
}, 1);
});
$(document).on('submit', 'form', function () {
var button = $(this).find(':submit');
setTimeout(function () {
button.attr('disabled', 'disabled');
}, 0);
});
The setTimeouts are needed. Otherwise, you could end up with a button that is disabled after clicked even when client-side validation fails. We have this in a global javascript file so that it is automatically applied to all of our forms.
Update 16 Nov 2020 by #seagull :
Replaced selector input[type="submit"] with :submit so it will work with <button type="submit" /> as well
The solution for mvc applications with mvc client side validation should be:
$('form').submit(function () {
if ($(this).valid()) {
$(':submit', this).attr('disabled', 'disabled');
}
});
Disable the button on Submit clicked. This can be done using JQuery/Java Script.
Look at this example on how to do this.
You can use this one. It includes unobtrusive jQuery validation.
$(document).on('submit', 'form', function () {
var buttons = $(this).find('[type="submit"]');
if ($(this).valid()) {
buttons.each(function (btn) {
$(buttons[btn]).prop('disabled', true);
});
} else {
buttons.each(function (btn) {
$(buttons[btn]).prop('disabled', false);
});
} });
For jQuery validation please incllude
~/Scripts/jquery.validate.min.js
~/Scripts/jquery.validate.unobtrusive.min.js
You can use ajax.BeginForm insted of html.BeginForm to achieve this, if you use OnSuccess insted of OnBegin you can be sure that your method execute successful and after that your button turn to deactivate,with ajax you stay
in current view and you can update your current view instead of redirection
#using (Ajax.BeginForm(
new AjaxOptions
{
HttpMethod = "post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "dive",
OnBegin="deactive"
}))
{
//body of your form same as Html.BeginForm
<input type="submit" id="Submit" value="Submit" />
}
and use this jquery in your form:
<script type="text/javascript" language="javascript"> function deactive() { $("#Submit").attr("disabled", true); }</script>
be careful for using ajax you have to call this scrip in the end of your page
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
Disabling the button is fine via JavaScript but what if the user has it disabled or they bypass it? If you use client side security then back it up with server side. I would use the PRG pattern here.
window.onload = function () {
$("#formId").submit(function() {// prevent the submit button to be pressed twice
$(this).find('#submitBtnId').attr('disabled', true);
$(this).find('#submitBtnId').text('Sending, please wait');
});
}

ASP.Net MVC 3.0 Ajax.BeginForm is redirecting to a Page?

In ASP.Net MVC 3.0 i am using a Ajax.Beginform
and hitting a JsonResult
on success of the form i am calling a jQuery Function.
but for some reason my form is redirecting to JsonAction
my View
#using (Ajax.BeginForm("ActionName", "Controller", null, new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "ShowResult"
}, new { id = "myform" }))
{
// All form Fields
<input type="submit" value="Continue" class="button standard" />
}
My controller
public JsonResult ActionName(FormCollection collection)
{
return Json(new { _status },JsonRequestBehavior.AllowGet);
}
jQuery
<script type="text/javascript">
function ShowResult(data) {
// alert("I am at ShowResult");
if (data.isRedirect) {
window.location.href = json.redirectUrl;
}
}
for some reason, when i click submit.
it runs the JSonResult and redirects the page to host/controller/actionname
I have included my
<script src="#Url.Content("jquery.unobtrusive-ajax.min.js")"></script>
in my layout.cshtml
can any one tell me what could be wrong?
I found the problem. Now i have to find the solution
on submit
I am validating my form
$("#myform").validate({
submitHandler: function (form) {
// my logic goes here....
}});
If i exclude the validation Ajax form works as expected.
But if i validate my form then ajax form is not working as expected
Thanks
when this happens its almost always because your script files aren't loaded
note from:
http://completedevelopment.blogspot.com/2011/02/unobstrusive-javascript-in-mvc-3-helps.html
Set the mentioned flag in the web.config:
Include a reference to the jQuery library ~/Scripts/jquery-1.4.4.js
Include a reference to the library that hooks this magic at ~/Scripts/jquery.unobtrusive-ajax.js
So load up fiddler http://fiddler2.com and see if the scripts are being called and loaded.

Creating a ajax login dialog box with MVC 3 and jQueryUI

I'm using Asp.Net MVC 3 (with Razor) and jQuery/jQueryUI to create a dialog login box.
I'm still quite new to these technologies and have run into a problem.
The login form is in a partial view, I use the following jQuery code to load it into the page:
$('#log-in').click(function () {
if (ServerModel.UserId == 0) {//User not logged in, open login dialog
$("<div></div>")
.addClass("dialog")
.addClass("form-dialog")
.attr("id", "login-dialog")
.appendTo("body")
.dialog({
title: 'LOGIN',
close: function () { $(this).remove() },
modal: true,
width: 323,
resizable: false
})
.load(ActionUrls.LogOn);
}
});
ActionUrls.LogOn, has the path for the Logon action method in the controller.
The partial view with the login form looks along these lines:
#using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "login-dialog" }))
{
//Login form fileds in here with submit button at the end
}
Here's the code for the controller:
[HttpGet]
public ActionResult LogOn()
{
return PartialView("_Logon");
}
[HttpPost]
public ActionResult LogOn(LogOnModel model)
{
if (ModelState.IsValid)
{
CustomSqlMembershipProvider provider = new CustomSqlMembershipProvider();
if (provider.ValidateUser(model.UserName, Security.ComputeHash(model.Password)))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// something failed, redisplay partial view with the model
return PartialView("_Logon", model);
}
This all works fine, however the problem I'm having, is that when the user is authenticated, as can be seen in the controller code. I try to RedirectToAction("Index", "Home"), this with the intent that the page should reload with the user logged in and the dialog closed.
However at the moment, just the login dialog box reloads with the whole page content in it. I understand that this is probably normal behavior, as I'm telling the form in the logon view to update the UpdateTargetId of the dialog box.
So the question is, can I reach my desired result of the whole page reloading and if so, how??
Any help and hints would be most appreciated.
/Ola
Instead of using a form parameter you can use jquerys ajax method and send in the username and password and in the success function of the ajax method if the user is successfully authenticated redirect the user to your index page.
note the index page should still have a way to determine that the user is authenticated or not else anyone can typein the url.
What do you think?
On your .load ajax call, the data that is returned contains redirect information. I'm not sure if this is only for JSON POSTS, but it's worth a try:
...
.load(ActionUrls.LogOn, function(data) {
if (data.redirect) {
window.location.href = data.redirect;
else {
// other
}
});
Update:
The callback event that you need to hook onto is the one that submits the login information, not the one that loads the login page. I asked you to hook onto the wrong ajax call on top, the one you need to latch onto is this one:
#using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "login-dialog" }))
{
//Login form fileds in here with submit button at the end
}
Unfortunately, I do not know how to hook onto that event. This article may help:
How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?
I noticed it's an old question, but I hope my reply may help to someone.
For something similar I redirected to a 'helper' page in the controller action, which contained (for me almost) only some JavaScript in the scipt tag (or you should link it of course).
In this case that's enough:
window.location.href = "http://www.foo.com";
...and I also find and close the dialog there:
$('#login-dialog').dialog('close');
For me it was well, but I also appreciate better solutions.

"UpdatePanel" in Razor (mvc 3)

Is there something like UpdatePanel (in ASPX) for Razor?
I want to refresh data (e.g. table, chart, ...) automaticly every 30 seconds.
Similar to clicking the following link every 30 seconds:
#Ajax.ActionLink("Refresh", "RefreshItems", new AjaxOptions() {
UpdateTargetId = "ItemList",
HttpMethod = "Post"})
Edit:
I may should add that the action link renders a partial view.
Code in cshtml:
<div id="ItemList">
#Html.Partial("_ItemList", Model)
</div>
Code in Controller:
[HttpPost]
public ActionResult RefreshItems() {
try {
// Fill List/Model
...
// Return Partial
return PartialView("_ItemList", model);
}
catch (Exception ex) {
return RedirectToAction("Index");
}
}
It would be create if the PartielView could refresh itself.
You can try something similar to the following using Jquery (have not tested though)
<script type="text/javascript">
$(document).ready(function() {
setInterval(function()
{
// not sure what the controller name is
$.post('<%= Url.Action("Refresh", "RefreshItems") %>', function(data) {
// Update the ItemList html element
$('#ItemList').html(data);
});
}
, 30000);
});
</script>
The above code should be placed in the containing page i.e. not the partial view page. Bear in mind that the a partial view is not a complete html page.
My initial guess is that this script can be placed in the partial and modified as follows. Make sure that the ajax data type is set to html.
<script type="text/javascript">
setInterval(function()
{
// not sure what the controller name is
$.post('<%= Url.Action("Refresh", "RefreshItems") %>', function(data) {
// Update the ItemList html element
$('#ItemList').html(data);
});
}
, 30000);
</script>
Another alternative is to store the javascript in a separate js file and use the Jquery getScript function in ajax success callback.
Well, if you don't need the AJAX expierience than use the HTML tag:
<meta http-equiv=”refresh” content=”30; URL=http://www.programmingfacts.com”>
go here: http://www.programmingfacts.com/auto-refresh-page-after-few-seconds-using-javascript/
If someone wants the complete code for a selfupdating partial view have a look!
Code of the Controller:
[HttpPost]
public ActionResult RefreshSelfUpdatingPartial() {
// Setting the Models Content
// ...
return PartialView("_SelfUpdatingPartial", model);
}
Code of the Partial (_SelfUpdatingPartial.cshtml):
#model YourModelClass
<script type="text/javascript">
setInterval(function () {
$.post('#Url.Action("RefreshSelfUpdatingPartial")', function (data) {
$('#SelfUpdatingPartialDiv').html(data);
}
);
}, 20000);
</script>
// Div
<div id="SelfUpdatingPartialDiv">
// Link to Refresh per Click
<p>
#Ajax.ActionLink("Aktualisieren", "RefreshFlatschels", new AjaxOptions() {
UpdateTargetId = "FlatschelList",
HttpMethod = "Post", InsertionMode = InsertionMode.Replace
})
</p>
// Your Code
// ...
</div>
Code to integrate the Partial in the "Main"-View (ViewWithSelfupdatingPartial.cs):
#Html.Partial("_FlatschelOverview", Model)
The <meta refresh ..> tag in HTML will work for you. Its the best option
Traditional controls don't works in ASP MVC
You could do it using Jquery timers http://plugins.jquery.com/project/timers
Other option could be to use the Delay function
In your target is as simple as refresh the whole page, this SO link will be of your interest: Auto refresh in ASP.NET MVC
Hope It Helps.

Resources