Using PagedList.Mvc for partial page - asp.net-mvc

I have four different tabs in one page and data for each tab is rendered by an ajax call using partial page. Data for tab is loaded by ajax post.
ajax call:
$('#movieDatabase').click(function () {
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'html',
type: 'POST',
url: '/Admin/GetMovieDatabase',
data: {},
success: function (data) {
$('#view16').html(data);
},
failure: function (response) {
alert('error');
$('#view16').html(response);
}
});
});
This ajax call rendered the partial page. Now I want to do is paging the movie came from database.For this I use PagedList.Mvc. But problem occurred in navigating movie from one page to another. It is done by:
#Html.PagedListPager((IPagedList)Model.MovieInforamtions, page => Url.Action("GetMovieDatabase", new { page }))
But when I click on next page it gives page not found error as I have not written any action in HTTPGet. And If I made above call by HTTPGet, I couldnot render all page but only partial page. My action is..
[HttpPost]
public ActionResult GetMovieDatabase(int? page)
{
var AdminGetMovieDatabaseViewModel = new AdminGetMovieDatabaseViewModel();
var allMovie = _AdminService.getAllMovieInfo();
var pageNumber = page ?? 1;
// if no page was specified in the querystring, default to the first page (1)
var onePageOfMovie = allMovie.ToPagedList(pageNumber, 5);
// will only contain 5 products max because of the pageSize
AdminGetMovieDatabaseViewModel.MovieInforamtions = onePageOfMovie;
return PartialView("MovieDataBasePartialPage", AdminGetMovieDatabaseViewModel);
}
Now How can I render the next page like in ajax call which is done previously?

I put the code in javascript section inside the partial view and works for me.
<script language ="javascript" type="text/javascript">
$('#movieDatabase').click(function () {
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'html',
type: 'POST',
url: '/Admin/GetMovieDatabase',
data: {},
success: function (data) {
$('#view16').html(data);
},
failure: function (response) {
alert('error');
$('#view16').html(response);
}
});
});
</script>

Related

How to use ajax in mvc?

I am a very beginner to mvc and ajax both.
I have tried many examples on net but I don't understand how ajax is used practically?
I have a controller named members which has GetAllMembers Method.
GetAllMembers returns a List<Members>
Now I want to use JQuery and ajax something like :
$(document).click(function () {
$.ajax({
url: "Members/GetAllMembers",
success: function () {
},
error: function () {
alert("Failed to get the members");
}
});
});
Is my URL right?
Upon success I want to display that List in a ListBox.
How can I get it? Can anyone give me a start?
$.ajax({
type: "POST",
url: "Members/GetAllMembers", //Your required php page
data: "id="+ data, //pass your required data here
success: function(response){ //You obtain the response that you echo from your controller
$('#Listbox').html(response); //The response is being printed inside the Listbox div that should have in your html page.
},
error: function () {
alert("Failed to get the members");
}
});
Hope this will help you.. :)
$(document).click(function () {
$.ajax({
url: "Members/GetAllMembers",
success: function (result) {
// do your code here
},
error: function () {
alert("Failed to get the members");
}
});
});
So your request give response in "result" variable. So you have to easily manage result variable value in foreach loop and set value in ListBox HTML.
Follow this example:
suppose you have this html:
<p>List Box - Single Select<br>
<select id="listBox" name="listbox">
</select>
</p>
So we have this js:
var template = '<option value="$value">$name</option>';
var getAllMembers = function() {
$.ajax({
url: 'Members/GetAllMembers',
dataType: 'json', //Assuming Members/GetAllMembers returns a json
success: function(response) {
$.each(response, function(index){
var option = template.replace(/\$value/g, this.value)
.replace(/\$name/g, this.name);
$('#listBox').append(option);
});
}
});
};
EDIT: Now you only need to call getAllMembers(); function.
Hope this help.
Pablo.

Dynamically added form ajax not work

I have a list of div's.
When I click on a button in a div I switch div content with partial view which contain form.
This is code that happens when I click on that button:
#Html.ActionLink("edit", "EditUserLanguage", "UserLanguage", new { userLanguageId = Model.UserLanguageId }, new { #class = "editButton" })
...
$(document).on('click', '.editButton', function (e) {
$.ajax({
url: this.href,
cache: false,
success: function (html) {
var id = $(e.target).closest("div").attr("id");
$("#" + id).empty();
$("#" + id).append(html);
}
});
return false;
});
Html (partial view) that I add has:
#using (Html.BeginForm("UpdateUserLanguage", "UserLanguage", FormMethod.Post, new { id = "updateUserLanagegeForm" }))
{
...
This main view where is the list of div's and where I add this new partial view I have this code:
$(function () {
$('#updateUserLanagegeForm').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
alert("work");
}
});
return false;
});
}); //update
When I click on submit action method is invoked and I get new partial view returned but not via ajax.
I only get that partial view returned. alert("work"); is never called.
What could be the reason that this ajax call doesn't work?
submit handler is not being attached to form as form gets loaded after dom ready. So change your code to -
$('body').on('submit','#updateUserLanagegeForm',(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
alert("work");
}
});
return false;
});
This will attach handler to form even if it is added dynamically.

Anyway to make use of jquery ui tabs spinner with pagemethods?

I am using Jquery ui tabs with asp.net webforms and I'm loading the content with ajax. I actually have two problems
I don't know how to load the content for the first tab load. Right now I use the tabsselect to load content via ajax.
$('#contentHolder').bind( "tabsselect", function(event, ui) {
// run ajax request
});
The build in spinner control only seems to work when I use actual paths for the href. But since I have to use pagemethods I need to use an id instead.
One
Two
Three
// ajax request to pagemethod
$.ajax...
Updated Code
// tab initializaztion
var $tabs = $('#followersTable').tabs({ spinner: 'Loading...' });
$tabs.bind("tabsselect", function(event, ui) {
//LoadTabContent(ui.index);
var request = {
'controlName': 'FollowersTab'
};
$(this).tabs({
ajaxOptions: {
type: "POST",
url: "ajax/Followers.aspx/LoadTabContent",
data: $.toJSON(request),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$(container).html(data.d);
},
error: function () {
}
}
})
});
For your first question:
$("your-tabs-selector-here").tabs( "load" , 0 ); this will force your tab first tab to be loaded via ajax.
If I didn't get it wrong; you could use [WebMethod] for your page methods and you can combine your page methods with UI Tabs ajaxOptions. You can play with ajaxOptions for return type and/or method name ..etc
$( "your-tabs-selector-here" ).tabs({
ajaxOptions: {
type: "POST",
url: "Default.aspx/PageMethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json"
}
});

Close FancyBox Before AJAX Post

I have following code.I show user a fancybox and they click Submit on Form I close fancybox and show them processing on page and do an AJAX post using JQuery. But some how fancybox gets stays open until AJAX form post is completed.Which creates confusion for user .
function BeginProcess(){
$.fancybox.close();
$("#imgProcess").attr("src", "/admin/images/loading_animation.gif");
$('#imgProcess').show();
PostAJAXForm();
}
function PostForm(FormData){
$.ajax({
type: "POST",
url: "process_image.jsp",
data: FormData,
contentType: "application/x-www-form-urlencoded",
async: false,
success: function(response) {
response = $.trim(response);
$('#imgProcess').delay(10000).hide();
return response;
},
error: function(xhr, ajaxOptions, thrownError) {
alert("There was an error. Please undo image and perform action again. " );
$('#lblProcess').delay(5000).hide();
return;
}
});
}
Here's a snippet:
var params = $(this).serialize();
var self = this;
$.ajax({
type: 'POST',
url: self.action,
data: params,
beforeSend: function(){
alert('Closing');
$.fancybox.close();
},
success: function(data){
alert('Finished processing form');
return false;
},
dataType: 'json'
});
Sorry if something is messed up or left out from that snippet - but you should get the idea.
You need to add $.fancybox.close() in Jquery' Ajax's beforeSend function.
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/ajaxSend/
This should help you out too
http://snipplr.com/view/47979/close-a-fancybox-when-you-submit-a-form-with-ajax

JQUERY GET operation not working

I'm having trouble with the following JQuery script
$('#extra_data').append('<div id="tabs-' + (tab_length + 1) + '"></div>');
$.get(url, function(data) {
$('#tabs-' + (tab_length + 1)).html(data);
});
My trouble is that the $.get(..) operation doesn't return any results - although when using firebug it shows the ajax call as expected.
Any clues?
Thanks.
Controller
<HttpPost()> _
Function GetPartialView() As ActionResult
If (Request.IsAjaxRequest()) Then
Return View("PVTest")
Else
Return View()
End If
End Function
I've filtered the request if it is Ajax. You can even pass an object to your partial view.
jQuery
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'Home/GetPartialView',
data: {},
dataType: 'json',
beforeSend: function(XMLHttpRequest) {
},
complete: function(XMLHttpRequest, textStatus) {
$('#extra_data').append(XMLHttpRequest.responseText);
}
});
});
</script>
Partial View (PVTest.ascx)
<%# Control Language="VB" Inherits="System.Web.Mvc.ViewUserControl" %>
<div id="01">
Hello World
</div>
Try load method:
$('#extra_data').append('');
$('#tabs-' + (tab_length + 1)).load(url)
I think you need to use Post and [HttpPost] in ASP.NET MVC, I think there is a security
issue related to GET.
I only seem to use Post operations and remember seeing something about security.
Will see if I can verify that...
ADDED:
see: ASP.NET MVC 2.0 JsonRequestBehavior Global Setting
I would use a POST, as Mark suggested:
$.ajax({
type: 'POST',
url: url,
data: { },
dataType: 'json',
beforeSend: function(XMLHttpRequest) {
},
complete: function(XMLHttpRequest, textStatus) {
var Response = $.parseJSON(XMLHttpRequest.responseText);
}
});
the Response should contain the JSON stream. You can append it to your element.
The controller should do something like this:
<HttpPost()> _
Function DoSomething() As ActionResult
Return (Json(myObject, JsonRequestBehavior.DenyGet))
End Function

Resources