Prevent page to navigate via MVC Ajax actionlink - asp.net-mvc

I am using asp.net (model view controller) razor view Ajax action link to navigate through pages in my website. My requirement is i will have to restrict the user and populates some popups before navigating to different page and leaving to the current page.
suppose there is view 1 (link) i am clicking on view 1 before loading view 1 page, i will have to show some popups..
I have implemented this functionality with html action link but i want it for ajax Action link too.
Thank you,

You can implement OnSuccess (or OnFailure or OnBegin or OnComplete) events in JavaScipt for Ajax.ActionLink() check below code -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script type="text/javascript">
function Test() {
alert('hi');
}
</script>
#Ajax.ActionLink("Rules", "LoadRules", new AjaxOptions { OnSuccess = "Test" })
Above code invokes Test JavaScript function, in there I am just alerting a message. But in your requirement, you can use some JQuery Modalpopups (or even a window.open()) to display popups for end user.

Related

How to execute Action method on click through scripts

In my app I have a button. By clicking this button I want to execute an action method.
This action method does not have any view.
My requirement is: "call this action method in on click event"
How can I execute the the method on the click event?
my Onclick event is
$('#Delete').click(function () {
#* #(Url.Action("Delete", new { id="cera123"}))*#
$.ajax({
url: '#(Url.Action("Delete", new { id="cera123"}))',
type: "GET",
success:function () {
alert('deleted');
}
});
my action method is
public ActionResult Delete(string id)
{
obj.EmpLi.RemoveAll(x => x.EmployeeId == id);
return RedirectToAction("Index", obj);
}
delete action is performed but i an see the result after voluntarily refreshing the page even though i gave RedirectToAction("Index")
thanks
$(function(){
$("#yourbutonId").click(function(){
$.get("/controller/action/id",function(data){
//data is what your action return
});
});
});
nilesh is right $.ajax is js,and $.get is sample use base on $.ajax
or $.post
to make these code work,you should ref jquery.js
Some background info...
If you come from the webforms and code-behind world is common to you that an HTML element calls a script in the code, but actually what asp.net webforms does is an http call to the script on the server. If you had an updatepanel, asp.net webforms would have done the same call via ajax.
That's the reason why in asp.net webforms the elements have the preceding asp: on their branded html tags. That way asp.net can convert their branded elements to real HTML elements.
The answer
The only way to execute the code of an action from an HTML element on-click event in asp.net MVC is by calling the URL that gets to that method. Either via ajax or by a request from the browser, an http request needs to be done.
With javascript you can listen when an element's on-click event is fired and then do some logic. If you're using jquery you can use the $.ajax() or $.get() methods to make a call to your action URL.

Using Link inside asp.net MVC4 PartialView to call and pass parameters to an action method and render another PartialView

Within a study course project, I have an MVC PartialView called _item, and inside it I put an href link (<a href = '#Url.Action("AddToShoppingCard", "Home", Model)'>) to call and pass parameters to an Action method (AddToShopingcart) in the Home controller which in turn renders another PartialView (_Footer) in the main _layout.
Although I could do that, but the problem is that when I click the ActionLink, it throws me outside the main _layout and displays only the _Footer content in the browser.
You could use an AJAX link instead:
#Ajax.ActionLink(
"Add to shopping cart",
"AddToShoppingCard",
"Home",
new AjaxOptions {
UpdateTargetId = "someDivYouWantToUpdateWithThePartial"
}
)
The Ajax.ActionLink helper will generate a normal <a> tag with the exception that it will add some HTML5 data-* attributes to it that are interpreted by the jquery.unobtrusive-ajax.js script (that you need to include to your page) and which will AJAXify this anchor. The AjaxOptions allow you to specify some properties of the AJAX request such as for example the id of some DOM element that you want to be updated when the AJAX request succeeds. In your case that could be some div that will receive the PartialView returned by the controller action that is being invoked with AJAX. This way only a portion of the page will be refreshed and the browser will not navigate away from it.

ASP.NET MVC 3 Ajax forms: Running JavaScript after DOM is updated

I have an MVC3 web project that includes very simple search form. It uses unobtrusive AJAX to bring back an HTML fragment containing the results in table form, and replaces an existing table. My problem is, I want to use the DataTables jQuery plug-in on the table to get sorting, paging, etc. But I cannot figure out the correct way to call the plug-in initialization code on the table.
What I have so far is this (this.Html.Script is just an extension method I wrote to auto-gen the script tags):
Search.cshtml:
#section ScriptSection
{
#this.Html.Script("libs/jquery.unobtrusive-ajax.min.js")
#this.Html.Script("libs/jquery.validate.js")
#this.Html.Script("libs/jquery.validate.unobtrusive.js")
#this.Html.Script("libs/jquery.dataTables.js")
<script type="text/javascript">
function initTable() {
$("table.datatable").dataTable();
}
</script>
}
#using ( this.Ajax.BeginForm("DoSearch", "Case", new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "results",
OnSuccess = "initTable"
}) )
{
<button type="submit" name="SearchType" value="date">Search</button>
}
<table id="results" class="datatable">
</table>
The problem is that initTable() appears to be called before the table I want is actually in the DOM. The outcome is that the results table is inserted into the page completely unstyled and with none of the dataTable features enabled.
Am I doing this right, or is there a different way to trigger the jQuery to run once the DOM has been updated?
put your code in:
$(document).ready(function() {
// Handler for .ready() called.
});
and see if that does it for you - the DOM should be completely loaded then.
Bleh, stupid mistake. jQuery DataTables needs the tags, which I wasn't using. Sorry for the noise.

ASP MVC + AJAX, trying to Update a div asynchronously

I'm new to Asp MVC, and I'm trying to accomplish a little async update (I'm using MVC3 RC2, with Razor, but I can manage with ASPX solutions too).
I have a Master page, which renders a shopping cart box on every page by calling Html.RenderAction("Cart","Shop"). The Cart action of the ShopController calls the database, etc, and outputs the results. This works.
First problem: if I put an ActionLink in this partial view (like Html.ActionLink("Remove")), then even if I call PartialView() from the Remove action, it renders only the shopping cart, and nothing else (in essence, my page disappears).
Second problem: There is a div called "cartContent" inside this partial view. I want to be able to put a link ANYWHERE (not just on the Master page or in the partial view), which when pressed calls a controller Action, and then updates ONLY the cartContent div based on the results. I've tried Ajax.ActionLink but it does the same as Html.ActionLink, even though I imported the Microsoft.MvcAjax js libs.
Also, if I solve the first problem, I want that to be async as well.
What solution do I use? I've tried setting UpdateTargetID to "cartContent", I've tried wrapping the cartContent into an Ajax.BeginForm, nothing. Do I HAVE to use jQuery (which I know nothing of)? Do I serialize some response to JSON, and update the div manually in Javascript? (I'm not really good at JS, I'm coming from the C# side of things)
You put a link wherever you want:
#Html.ActionLink("remove item", "remove", "somecontroller",
new { id = Model.Id }, new { #class = "remove" })
And then in a separate javascript file:
$(function() {
$('.remove').click(function() {
// when the link is clicked
// perform an ajax request:
$.ajax({
url: this.href,
type: 'delete',
success: function(result) {
// when the AJAX call succeed do something with the result
// for example if the controller action returned a partial
// then you could show this partial in some div
$('#someDivId').html(result);
}
});
// don't forget to cancel the default action by returning false
return false;
});
});
Remark: if the div you are updating contains also the link then you might need to use the .live() function or the click event handler will not work the second time because the DOM will be modified:
$('.remove').live('click', function() {
...
});

Rebinding JQuery Event Handlers after MicrosoftAjax returns a PartialView

I am playing around with AJAX functionality using ASP.NET MVC. I have created a page with a menu of categories generated from a database which when clicked makes an AJAX request to a Controller and then a Controller returns a PartialView.
<% foreach (var item in Model.Categories)
{ %>
<li>
<%= Ajax.ActionLink(item.CategoryName,
"Index", "Home",
new { id = item.CategoryID },
new AjaxOptions { UpdateTargetId = "gallery" })%>
</li>
<% } %>
[HttpPost]
public ActionResult Index(int id)
{
List<Image> images = imageRepository.getCategoryImages(id).ToList();
return PartialView("gallery", images);
}
The gallery div contains a number of images, on first load it has every image which is stored in a database. I have used lightbox a JQuery plugin so when an Thumbnail is click it enlarges and a user can click through the images. When the partial view is returned the lightbox event handler is no longer bound.
$(function () {
$('#gallery a').lightBox();
});
Is it possible to somehow trigger a Javascript function to rebind the handler after the M$AJAX request completes?
This is part of a series of projects I intend to undertake to teach myself how to do some cool things with AJAX in ASP.NET MVC. I intend to release the code on my website once complete so others can learn like I have. I tend to find there are so many example with JQuery -> PHP -> MySQL the open source stack. But very little with ASP.NET MVC.
Thanks,
Jon
One of the AjaxOptions properties is an OnSuccess property that will call some JavaScript code after a successful AJAX request. Set its value to the name of a JavaScript function that then uses jQuery to activate the LightBox script.
new AjaxOptions { UpdateTargetId = "gallery", OnSuccess="ActivateLightBox" })
And some script:
<script ...>
function ActivateLightBox() {
$(function () {
$('#gallery a').lightBox();
});
}
</script>
You have two options. Either add that javascript to the gallery view, so it gets run when the partial view is loaded or the better solutions is the one that #Eilon just got in there first with.

Resources