Lazy Loading Infinite Scroll in mvc 3 - asp.net-mvc-3

I perform the data fetching by using a stored procedure which accepts page size, and page index.
I would like to be able to call the action method List from the view with the page size and page index parameters, which in turn will call the stored procedure.
That is doable. But I'm trying to do this with jquery lazy loading.
So, the view will first fetch the results in the first page (let's say page size = 10 and page index = 1). Next, if the user scrolls down, the next page will be fetched, which means the view will call the the List method with page size = 20 and page index = 1. this will countinue until all the pages from the results were fetched.
Is this scenario reasonable, and if so how do Implement it using jquery? if this scenario is not reasonable, what are the other options?
Controller:
[HttpPost]
public ActionResult List(int pageSize, int pageIndex)
{ ... }
The jquery I have so far:
$(document).ready(function () {
$("#search-button").click(function () {
var url = '#Url.Action("List", "Home")';
url = url + "?pageSize=10&pageIndex=1";
$.post(url, function (data) {
$('#listcontainer').fadeOut(0, function () {
$('#listcontainer').html(data);
$('#listcontainer').fadeIn('fast');
});
});
});
});

Related

How to present partial view in jQuery dialog without navigating to another page

I have two controllers, A and B. A is responsible for representing some data in a grid view. Assume I have a button called "ShowInfo" which brings additional info about the selected record. And to retrieve the info about the selected record is the job of controller B.
The info is so little that it'd take just a tiny place in the corner if I navigate to another view. So I thought I'd rather bring that info inside a jQuery dialog without navigating to anywhere. But I'm a bit confused as to how to do it.
Here's the action method in controller B that is responsible for providing that info in a partial view.
public class BController:Controller{
public ActionResult GetInfo(int recordID){
RecordInfo info=RecordsRepository.GetRecordInfoById(recordID);
return PartialView(viewName:"RecordInfo",model:info);
}
}
I don't know, maybe the action method needs to different. Maybe I should return JSON instead of Partial view, but anyway, how do I do that?
You can use the jquery .get or .load methods. For example, to replace the contents of <div id="SomeElement"></div> with the partial view returned by GetInfo()
$('#ShowInfo').click(function() {
var url = '#Url.Action("GetInfo", "B")';
var ID = someValue; // the value to pass to the GetInfo method
$.get(url, { recordID: ID }, function(data) {
$('#someElement').html(data);
});
});
You can use Jquery ajax to achieve this.
Wrtire jquery ajax on the view page and call the partial view action from ajax.
receive the result in html format and replace it in the dialog box.
Put following code on main view page(ShowInfo button page)
$(document).ready(function(){
$("#ShowInfo").on("click",function(){ ///give id to showinfo button and attr data-id is record id
var id=$(this).attr("data-id");
$.ajax({
type: "POST",
url: "B/GetInfo",
data: JSON.stringify({ recordID: id }),
dataType: "html",
success: function (html)
{
////put the html response in dialog box
}
});
})
});

Prevent browser caching of MVC partial pages as full pages (on back/forward)

I have an iphone-style list-view system for navigation of a website that looks like this:
The URL is changed dynamically when a panel is loaded via AJAX and the same URL is placed in the browser address bar with puststate. This a allows a page refresh to reload the current page:
this.Historyjs.pushState({}, "", url);
To make this work the pages can return themselves as either a partial page, or a full page. The code to detect the difference is a base controller and looks like:
public bool IsPartialPage
{
get
{
// ListViewer will strip out HTML from a full page if this occurs
return Request.IsAjaxRequest() || !string.IsNullOrEmpty(Request["partial"]);
}
}
An example controller action looks like this (note the Partial View cache expiry):
[OutputCache(Duration=1)]
public ActionResult ListViewerDocumentation()
{
if (!base.IsPartialPage)
{
ViewBag.Layout = "~/Views/Shared/_ListViewLayout.cshtml";
}
return PartialView();
}
The problem I have is that when you navigate using the Browser's back and forward buttons, it will occasionally decide that a previously partial page is sufficient to become the entire page and does not make a call to the server (checked with Fiddler2) and so looks like this:
Any suggestions on a method that will ensure back and forward navigation always pull back a full page and not from its cache of Ajax requests? Is it simply a matter of making the Ajax calls unique, or will the vanilla URL from the back/forward still match?
Turns out the trick is to turn off caching on the Ajax request that pulls the partial pages, not on the server as that is never hit (the light suddenly came on after writing the above question):
$.ajax(
{
cache: false, // << Added this
url: url,
type: "GET",
error: function (jqXHR, textStatus: string, errorThrown: string)
{
// On error (eg. "not found") empty out the display
THIS._removeContent();
},
success: function (data: string, textStatus: string, jqXHR)
{
var $data = $(data);
THIS._insertContent($data, function ()
{
});
}
});
The cache false also apparently ensures the browser will not reuse the page on page back/forward operations.

passing data to jquery modal aside from adding parameters to url?

On click of a #dtDelete button I am opening an ajax modal in bootstrap 3. I am also passing a parameter, selected, along with it and using $_GET on the php page to retrieve it.
As the value of selected may or may not be extremely large I think I should avoid passing the value this way / using $_GET.
How the heck can I pass values other than this method? Due to the nature of opening the modal (loading it then showing it) I am stuck on any other ways.
$('#dtDelete').on('click', function () {
//open the modal with selected parameter attached
$('#modal-ajax').load('/modals/m_keystroke_delete.php?selected='+selected);
$('#modal-ajax').modal('show');
});
Pass a data object as a second param to load for it to make a POST request.
$('#dtDelete').on('click', function () {
var data = { 'propertyA': 'extremely large data' };
//open the modal with selected parameter attached
$('#modal-ajax').load(
'/modals/m_keystroke_delete.php?selected=' + selected, // url
data, // data
function(responseText, textStatus, XMLHttpRequest) { } // complete callback
);
$('#modal-ajax').modal('show');
});
You can even pass your "selected" param through the POST request and use $_POST or even $_REQUEST to retrieve the data. Also notice that the modal now shows once the request has completed.
$('#dtDelete').on('click', function () {
var data = {
'selected': selected
'largeData': '...'
};
$('#modal-ajax').load(
'/modals/m_keystroke_delete.php',
data,
function() {
// Invoke the delete-function
deleteComp();
// Show the modal
$(this).modal('show');
}
);
});

How to make Ext.Ajax.request only after form fields are loaded completely

I have a function which uses following code to fetch form values-
var formValues = this.myForm.getForm().getValues();
MyForm contains a combobox which loads with form. (There are two separate requests for combo load and form load)
As these two requests are loading at the same time, above code do not return combo values as they are still loading.
Is there any way to check whether combo values are loaded and then only send ajax request for form load so that above code will have all form values?
Edited:
LoadComboBox function just fills the data with some store.
Following is the code for form load-
loadFormGrid: function (){
var allValues = this.myForm.getForm().getValues(); // this do not consider combobox values
Ext.Ajax.request({
params: {action: 'getList', data : allValues },
// ... some code
});
}
I would do something like:
On the success event of the combo box load, call the load method of the form/make your ajax request to populate the fields of the form.
EDIT:
Here is what I mean:
The place where you instantiate your ComboBox probably looks like:
var combo = new Ext.form.ComboBox({
store : new someStoreType({
//add to catch the loaded event
listeners : {
'load' : function(store, recs, options){
loadFormGrid();
}
}
})
});
The store listener above ('load') will catch when the combo box is loaded and will call the function to populate/load the form.

ASP.NET MVC 3 display list of object without reloading web page

I have ASP.NET MVC 3 web app and List of objects
List<ConversionModel> Queue
I would like to display list of ConversionModel objects in one web page and refresh display every five seconds without reloading web page. I am new to MVC 3 and can't find any example.
You could use AJAX for this, but I don't think that has a good impact on your server (at least doing so every five seconds for every user on your site).
Client-side:
<script type="text/javascript">
// This is to refresh the items every 5 seconds (5000 milliseconds)
setInterval(getMyData, 5000);
function getMyData() {
// Using $.getJSON for simplicity, but try to use $.ajax or $.post
$.getJSON('/MyController/MyAction', function(response) {
var items = response.d.items;
// Iterate through the items here and add the items to your web page
});
}
</script>
Server-side:
public JsonResult MyAction()
{
List<ConversionModel> conversionModels = GetMyDataSomewhere();
return Json(new {
items = conversionModels
}, JsonRequestBehaviour.AllowGet);
}
If updating the view each five seconds is all you need, you could get away with simple ajax combined with a timer. See
jQuery ajax function
JavaScript setTimeout() function
Third, you will need to have an action method in one of your controllers fetching the set of ConversionModels from the database and generating a response from it (either JSON or directly a HTML markup).
If you read the documentation for the $.ajax() function, I believe you will see how the pieces fit in together.
If, however, you want to be more flexible than just polling the server each five seconds regardless of the real activity, you may want to check on SignalR, a great library for pushing data from server to the client (e.g. a browser).
use jQuery an make ajax requests every x minutes to the controller that will return a partial view with a model as List.
javascript on your main page could look like this:
function timerMethod() {
$.ajax({
type: "get"
url: "/Controller/Action",
cache: false,
success: function(result){
$("#partialContainer").html(result);
}
});
var timerId = setInterval(timerMethod, 5000); // 5 seconds
Controller/Action is your action that return partial view.
You also need to create a view with name Action in Views\Controller and write it so that it displays all the objects in the model (model should be of type List<ConversionModel>). Hope that helps

Resources