unwanted multiple ajax request to an action in asp.net mvc - asp.net-mvc

I am developing an asp.net mvc application and have ajax calls on my page. Here is a form which I load by ajax call to page :
The form is located in a partial view
<div id="CreateCultureArea">
<%
using (Ajax.BeginForm("CreateCulture", "Admin", new AjaxOptions() { OnSuccess = "handleCreateCulture" }))
{ %>
.....
<% } %>
</div>
Code Updated
The following script is located in a view :
Create Culture
<script type="text/javascript">
$('.CreateCulture').live('click', function (e) {
e.preventDefault();
var idval = this.id;
$.ajax({
url: "/Admin/CreateCulture",
dataType: 'html',
data: { id: idval },
success: function (mydata) {
$("#CultureContentArea").empty();
$("#CultureContentArea").empty().hide().append(mydata).fadeIn(2000);
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
},
type: "GET"
});
return false;
})
</script>
When users click on a link with CreateCulture class, the form is loaded to page. But as I saw the requests in firebug, it calls the action multiple times. I read similar posts like mine on stackoverflow.com and most of them suggested removing repetitive "jquery.unobtrusive-ajax.min.js" calss in page, but as I saw the output page I only see on link to the "jquery.unobtrusive-ajax.min.js" script.

The problem is that #Ajax.BeginForm emits a form that has the attribute data-ajax="true". In the unobtrusive AJAX script (see the non-minified version and look for calls to asyncRequest). So by calling $.ajax yourself, you are repeating the work of #Ajax.BeginForm. Just take out your call to $.ajax and you'll see your action get called only once.
If you need to take action after the AJAX call completes, set the OnComplete property of AjaxOptions in your call to Ajax.BeginForm.

Make sure that you have not multiple .js refrence in page
<script src='/Scripts/jquery.unobtrusive-ajax.min.js'></script>
<script src="/Scripts/jquery.validate.min.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>

The problem was that I put some scripts in partial view and each time it duplicated by loading this. So I put the scripts all in on page and problem solved.

Related

Ajax request not fired form partial page when the main page also has an ajax request

In my _layout.cshtml I have a partial view that includes js trough requirejs.
<script data-main="/Scripts/Search" src="/Scripts/require.js"></script>
In this js file I use the following to populate a knockout vm.
$.getJSON("/Search/Index", function (data) {
self.availableCities(data.AvailableCities);
});
This works well on all pages except when my main view also has an ajax request.
<script data-main="/Scripts/Index" src="/Scripts/require.js"></script>
$.getJSON("/Property/All", function (data) {
self.properties(data);
});
Here is my require config, it is the same for the partial and the main view.
require.config({
baseUrl: "/Scripts",
paths: {
"text": "text",
"knockout": "knockout-3.3.0",
"jquery": "jquery-2.1.3.min"
},
shim: {
"jquery": { exports: "$" }
}
});
When the main page has an ajax request only this request is fired, I am not sure how to fix this. It looks like a configuration issue, tested it in both Firefox an Chrome so it does not appear to be browser specific.
It turns out having multiple <script data-main="/Scripts/Search" src="/Scripts/require.js"></script> tags in one page isn't such a bright idea.
I figured it out after some more research,
this question has a good solution if you run into a similar problem.
Basically you need one 'main.js' file and add the other page components via the require logic.
Edit:
Doing this may result in the following knockout error:
Error: You cannot apply bindings multiple times to the same element.
To fix this I have used the following binding handler:
ko.bindingHandlers.stopBinding = {
init: function () {
return { controlsDescendantBindings: true };
}
};
To enable this binding handler on containerless elements use the following:
ko.virtualElements.allowedBindings.stopBinding = true;
Apply the following binding around the partial view. To prevent the main-page from binding to the elements in the partial.
<!-- ko stopBinding: true-->
<!-- /ko -->
Finally use ko.applyBinings on the partialview like this:
ko.applyBindings(new partialViewModel(), document.getElementById("your-partial"));

MVC : How to clear session and close the current browser tab on click of logout link?

I am trying to clear the session and the close the browser tab on logout link click. Please help me to do this.
Thanks in advance
You're trying to achieve two different things, one of which is a server-side concern, the other a client-side concern.
You could try splitting up these concerns, for example:
A: Using some Post/Redirect/Get laced with tab-closing javascript
Post to Logout controller method
Redirect to /LogoutSuccess
Put some javascript that closes the browser tab on body load, in the LogoutSuccess view.
B: A more client-side approach
Perform (in your javascript) a http GET to /Logout
Upon 200 OK response, execute some javascript that closes the browser tab.
Session.Abandon();
or
Session.Clean();
or
Session[".."]=null;
close windows you can use js
windows.close();
in some browser,it will pop a confirm
You can send an ajax request to to an action method which clears the session variables and in the call back, you can close the window.
<a id=logoutLink">Logout</a>
<script type="text/javascript">
$(function(){
$("#logoutLink").click(function(e){
e.preventDefault();
$.post("#Url.Action("Logout","User")",function(res){
if(res.status==="done")
{
//close the window now.
window.close();
}
});
});
});
</script>
Now in your UserController, Add the Logout action method
public class UserController : Controller
{
[HttpPost]
public ActionResult Logout()
{
Session.Abandon();
return Json(new { status="done"});
}
}
Reference:
MVC for clossing browser tab when logout
This code is from MSDN. I have added the async : false to the jQuery call as that is the key to ensure that the call flushes the Server Side session and then the window closes.
<script type="text/javascript">
$(document).ready(function () {
window.addEventListener('beforeunload',recordeCloseTime);
});
function recordeCloseTime() {
$.ajax({
type: "POST",
async: false,
url: "ServiceToClearSession.asmx/RecordCloseTime",
});
}
</script>

jquery form Submit success and Failure Callback

I'm building an ASP.Net Mvc 4 app. I see that i can use a #Ajax.BeginForm to perform a POST request asynchronously. Also API seems to have an OnSuccess and On Failure parameter, which takes in the javascript function to be executed on success/failure. I've read that this works for MS Ajax, but would this work for jquery as well ? I can't seem to get it working with jquery alone
#using (Ajax.BeginForm("Create", "Comment", null, new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "Post",
OnSuccess = "people.successfulSave",
OnFailure = "people.saveFailure"
},
If not then, i want to do it with jquery via form submit. Currently I'm doing
$('#commentSubmitInput').click(function() {
$("#commentForm").submit();
}
to submit the form. But in my controller I'm doing some model validation and return back Html with model errors if the model is invalid, else return a partial view with updated html. Now i read that i could bind the ajax call to a function with the below syntax
$("#commentForm").bind('ajax:complete', function () {
alert('bla');
});
but, is there a way I can have success and failure callback for form submit instead ?? kind of like the Jquery ajax call syntax
$.ajax({
url: $(this).attr('ajaxUrl'),
type: 'POST',
success: function (data) {
$("#comment_" + data.Id).remove();
},
error: function (data) {
window.location.reload();
}
});
Any help/suggestion is appreciated.
Thanks in advance !
As far as I can help you is to check this: ASP.NET MVC 4 - Ajax.BeginForm and html5
And maybe this (you can get an idea or two here): MVC4 - Ajax.BeginForm and Partial view gives 'undefined'

ASP.NET MVC multiple forms, staying on same page

I have forms located in multiple areas in my layout page (not nested).
I have a partial view which performs a post to controller action.
What action result do I return in that post to keep the user on the current page?
Is jquery/ajax my only option? I would rather a solution that didn't depend on javascript, maybe even a solution that degrades nicely.
You can use the Request.Referrer property to see what page the user has come from and then just use that to redirect them back there.
This does introduce other issues, e.g. losing ModelState, so you'll have to design for that. Also note that some users can block sending referrer information in their requests to the server - so the Referrer property can be null.
I would recommend using AJAX and then falling back on this.
You just need to do a RedirectToAction("") back to your main view.
To post a form without submitting the whole page, which refreshes the browser, you need to use Ajax/jQuery. The degraded solution is to submit the whole page like you would with a normal form.
Here's how I do it with jQuery.
Html:
<div id="RequestButtonDiv">
<button id="RequestButton" name="Request" type="button">Request</button>
</div>
This calls AddToCart on my Request controller when the RequestButton button is clicked. The response is placed inside the RequestButtonDiv element.
<script type="text/javascript">
$(document).ready(function () {
$('#RequestButton').click(function (event) {
$('#RequestButton').text('Processing...');
$('#RequestButton').attr('disabled', true);
submitRequest();
});
});
function submitRequest() {
$.ajax({
url: '<%: Url.Action("AddToCart", "Request", new { id = Model.RowId, randomId = new Random().Next(1, 999999) } ) %>',
success: function (response) {
// update status element
$('#RequestButtonDiv').html(response);
}
});
}
</script>
Controller action:
public ActionResult AddToCart(int id)
{
var user = AccountController.GetUserFromSession();
user.RequestCart.AddAsset(id);
return View("~/Views/Assets/Details_AddToCart.ascx");
}
The controller returns a partial view. You could also return Content("some stuff") instead.
Holler if you have questions or need more detail.

MVC-pop up windows

I need to create pop up windows in mvc(not new tab in browser). Does anyone know how to do this?
One possibility is to use jquery ui dialog.
EDIT
The idea would be to have an ajax action that returns a partial view. The result of that action (html) is placed inside the container of the popup and on the success handler of the ajax call you open the popup. Here is some sample code:
#Ajax.ActionLink("Open popup", "SomeAction", new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "result", InsertionMode = InsertionMode.Replace, OnSuccess="openPopup" })<br />
<div id="result" style="display:none;"></div>
<script type="text/javascript">
$(document).ready(function() {
$("#result").dialog({
autoOpen: false,
title: 'Title',
width: 500,
height: 'auto',
modal: true
});
});
function openPopup() {
$("#result").dialog("open");
}
</script>
Then you have to add the action in the controller that returns the partial view
[HttpGet]
public PartialViewResult SomeAction()
{
return PartialView();
}
Place whatever you need in the partial view, you may also include parameters in the action, etc.
Good luck!
Most obvious way is using one of js frameworks. Personally I prefere jQuery UI dialog control.
Please check http://jqueryui.com/demos/dialog/ for detailed information about it.
Also you may check ASP.NET MVC modal dialog/popup best practice (it's question similar to yours)
Of course if you need some simple popup you always may use alert('Im popup');
Update according your latest request
To open some url in new window you may use next javascript:
function OpenDialog() {
window.open("some url", "DialogName", "height=200,width=200,modal=yes,alwaysRaised=yes");
}
But result really depends on browser. Most of them open this modal window not in new tab but in new browser instance.
This topic might help you aswell:
JavaScript open in a new window, not tab

Resources