How can i do paging in asp.net mvc3? - asp.net-mvc

I am working on asp.net mvc3 application and have many records coming from database. I want to display only 10 records first then user can click on button to see next 10 records and so on... Like facebook wall posting more records.
How can I implement this thing in my application using jQuery and ajax?
How can I control display data in view using paging?
I am using this to get 10 records but I want to display all records using more record button
var Entity = (from a
in context.Data
where <Condition>
select a).Take(10);

The following articles should give you an idea :
http://weblogs.asp.net/andrewrea/archive/2008/07/01/asp-net-mvc-quot-pager-quot-html-helper.aspx
http://weblogs.asp.net/gunnarpeipman/archive/2010/02/21/simple-pager-for-asp-net-mvc.aspx
On the other hand, you can implement it like this :
Get the nuget package called TugberkUg.MVC
Then, your controller should look like below :
public ActionResult Index(int page = 0) {
const int pageSize = 10;
#region _filter the model
IQueryable<myModel> model = _myrepo.GetAll()
#endregion
#region _convert the model to paginatedList
var paginatedModel =
new TugberkUg.MVC.Helpers.PaginatedList<myModel>(model, page, pageSize);
#endregion
return View(paginatedModel);
}
And, here how your controller should look like :
#model TugberkUg.MVC.Helpers.PaginatedList<myModel>
#foreach(var item in Model) {
<p>#item.id</p>
}
You need to handle the pager as well and here is a sample for you :
ASP.NET MVC PaginatedList Pager - Put wise "..." after certain point
This TugberkUg.MVC.Helpers.PaginatedList class will provide all the necessary fields for pager.

I'm not aware of any .net library that will do pagination for you out of the box, so I will roll out a DIY solution for you to think about.
How can i implement this thing in my application using jquery and ajax?
It is probably wise to have a specific Controller for ajax requests. Just have a separate Area (Ajax), and send your ajax requests to that url you set up.
How can i control display data in view using paging?
Set up a controller that takes in a "page" parameter.
public ActionResult GetData(int? page){
// page is nullable to allow for default page
// Do your query here to get the specific page.
}
I'm not sure if you require more information other than this. If I were trying to do what you were doing, this is what I would do. Hope that helps.

If your are using Webgrid to display data then rowsperpage will do.
var grid = new WebGrid(source: Model, selectionFieldName: "SelectedRow", rowsPerPage: 10, canPage: true, canSort: true);

I would suggest using a telerik mvc control. They are really easy to use, powerful and free.
www.telerik.com

Related

MVC: Displaying dynamic forms based on URL arguments

I am trying to generate content within a view based on a URL parameter.
For example:
10 companies, 30 users each
A user from company Google clicks a distributed icon that opens
www.****tickets.com/ticket/?c=Google
A custom ticketing page with textboxes, dropdownlists with
'Google-specific' categories and the Google logo is displayed.
All of this data will be handled by a common controller
I have lots of plans for this site, but this is step #1. I am pretty new to MVC, but I have a page propped up that has Users/Groups/Roles. I'm unsure if there would be a better way to implement this, such as Javascript.
EDIT: It looks like MVC Dynamic Forms could be useful for this application. Researching it now.
Your controller method for handling the URL /ticket should accept an optional parameter c. This will then automatically be populated by the value in the querystring. You can then hold this in a model and pass it into the view.
The code will be something like
[HttpGet]
public ActionResult Ticket(string c = null)
{
//Get some data based on c
var model = new TicketModel
{
Company = c,
SomeDropdownValues = StuffYouReadFromTheDbUsingParameterC,
LogoPath = PathYouHaveCalculatedUsingParameterC
};
return View(model);
}
If you don't know how to use a model within a view look up the term "model binding". This article explains it clearly.

ASP.net MVC create related object using partials

I am relatively new to ASP and MVC but have got on ok so far. I am using the DB first approach and have my DB tables all setup (it is an existing DB cleaned up with FKs etc).
I have a route of FKs:
Contact
- LettingContact
- Landlord
- Tenant
I would like to be able to use partials to display the data e.g. /Contact/_Create will hold the Contact info i.e. Title, Forename, Surname and will be used both by /Contact/Create and /Tenant/Create. I managed to get it working not using the partials and just using the field on the Tenant/Create html form and showing the relevant data from the models. To the Tenant/Create in the controller i did the following (doing the following stopped me getting null exceptions in the partial)
Tenant tenant = new Tenant();
LettingsContact lettingsContact = new LettingsContact();
Contact contact = new Contact();
tenant.LettingsContact = letContact;
tenant.LettingsContact.Contact = contact;
return View(tenant)
Now the View is
//using Html.BeginForm etc
#{
Html.RenderPartial("../Contact/_Create", Model.LettingsContact.Contact);
Html.RenderPartial("_Create", Model);
}
<input type="submit" value="create">
//rest of html
Now when I click the submit button it goes to my /Tenant/Create post event.
[HttpPost]
public ActionResult Create(Tenant tenant)
{
if (ModelState.IsValue)
{
tenant.ContactID = Guid.NewGuid();
tenant.LettingsContact.Contact.ContactID = tenant.ContactID;
db.Tenants.AddObject(tenant);
db.SaveChanges();
return RedirectToAction("Index");
}
}
However the line which reads tenant.LettingContact.Contact.ContactID crashes will a NullReferenceException to the LettingsContact is null. Any reason why the partials are not maintaining the Models?
Also if there is a better way of doing this please let me know as this is still very new to me.
The reason I want to use partials is that it will enable me to reuse the forms in jQuery modal forms etc.
If you want a form to post back information that you don't want displayed on the page you should use a hidden field. Have a look at Html.Hidden() and Html.HiddenFor().
Hidden on msdn: http://msdn.microsoft.com/en-us/library/system.web.mvc.html.inputextensions.hidden.aspx
HiddenFor on msdn: http://msdn.microsoft.com/en-us/library/system.web.mvc.html.inputextensions.hiddenfor.aspx

MVC generic search and model validatation issue

I'll explain a generic scenario. To explain my problem, I'd request some patience until I explain how I've implemented my Search page. I've a [Users] table and an [Address] table based on which I've derived a VIEW in SQL - [vw_User_Addr]. I'm using L2S so that I'll get a strongly typed vw_User_Addr class.
Now I've a search page so apparently I'll derive it from this class like:
<%# Page Title="User Search" ... Inherits="System.Web.Mvc.ViewPage<MyDAL.vw_User_Addr>" %>
My List action returns a List which I use in the View to form the Grid table. Everything is fine till here. Now I want to implement search on this page. So this is what I found -
In Controller during the List Action I create ViewData["Usr"] = new vw_User_Addr();
In my View I do:
<% MyDAL.vw_User_Addr usr =
((MyDAL.vw_User_Addr)(ViewData["Usr"]));
%>
Then I use this "usr" object to bind my search control like:
<%= Html.TextBox("FirstName",
usr.FirstName)%>
Finally in my HttpPost handler action I object vw_User_Addr like:
[HttpPost] public ActionResult
List(vw_User_Addr searchObj){...}
I use this searchObj to extract the values user might have populated in the search controls and then I perform search.
So, I hope I explained well. This is how I do my search in MVC2. Here're my concerns/questions:
When I click on the search image-button I get a postback but it fires a ModelValidation which gives error. Not with all but atleast those which are int (i.e. like Roles dropdown search control) - how to handle that?
After a lot of R&D I've settled that I've to either do a ModelState.Clear(); or a more complex way to handle this. Is there a better option?
Is there a better way to achieve the search-implementation explained above? Am I using the standard\best way to do search in MVC?
At core-level, can I make L2S understand that this is an SQL-View so its Readonly and all the fields can be NULL - so that the Mr.DefaultModelValidator doesn't perform such illogical validations?
If 4. is viable can I set the properties of all the fields in the L2S view to be readonly to give it a try?
Thank you for your precious time and review. Pls guide me if I'm not on the track. I believe this is the simplest search-scenario and so it has to be easy. Just need to find the missing links.
I implemented an ActionFilterAttribute [SkipModelValidation] which avoids/eliminates unwanted model validation for search pages.
Ref: How to disable validation in a HttpPost action in ASP.NET MVC 3?
public class SkipModelValidationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//Get ModelState
ModelStateDictionary dict = ((Controller)filterContext.Controller).ModelState;
if (dict != null && !dict.IsValid)
dict.Clear();
base.OnActionExecuting(filterContext);
}
}

Retrieving and caching HTML from website using ASP.NET MVC 3

I want a partial view that display some stuff from a website that is not under my control.
The data on the website is only available through HTML, and thus I can only retrieve it by querying the web site and parsing the HTML. (The website holds a list of 50 elements, and I only want the top 10.)
Now, the data from the website is not changing very frequently, so I imagine that I can retrieve the HTML on an hourly basis, and displaying a cached version on my web site.
How can I accomplish this in ASP.NET MVC 3?
Ignoring the MVC3 requirement for now, you should look to using WebClient to grab the html from the website. You can do something like:
var client = new WebClient();
var html = Encoding.UTF8.GetString(client.DownloadData("http://www.somedomain.com"));
If you need to tailor your request, I'd recommend looking at HttpWebRequest, HttpWebResponse. Now that you can grab the html, you need to consider your caching mechanism, possibly in the ASP.NET runtime?
public ActionResult GetHtml()
{
if (HttpRuntime.Cache["html"] == null)
GetHtmlInternal();
return Content((string)HttpRuntime.Cache["html"], "text/html");
}
private void GetHtmlInternal()
{
var html = // get html here.
HttpRuntime.Cache.Insert("html", html, null, DateTime.Now.AddMinutes(60), Cache.NoSlidingExpiration);
}
The first solution that comes to mind is to create an action in a controller that makes an Http request to the remote web page and parses the html you want to return to your own page and then set output caching on your action.
Edit:
What controller to put the action in would depend on the structure of your web site and whether the partial view would be visible on all views or just a specific view. If the partial is visible in all views I'd either place it in the Home controller or create a "General" controller (if I anticipated more actions would go in such a controller).
If you want to manipulate the result I would probably make a model and partial view for the list. If you want to take a part of the returned html and output it as it is I would use the same method as in the answer by Matthew Abbott:
return Content(yourHtmlString);
The end would look something like this:
[OutputCache(Duration = 3600)]
public ActionResult RemoteList()
{
var client = new WebClient();
var html = Encoding.UTF8.GetString(client.DownloadData("http://www.somedomain.com"));
// Do your manipulation here...
return Content(html);
}
(Some of the above code was borrowed from the post by Matthew Abbott.)
You could just add OutputCache attribute on your action and set OutputCache.Duration Property to 3600 seconds (1 hour)

ASP.NET MVC 2 Without Data Model Query

Can anyone tell me how to use ASP.NET MVC 2 without data models...i mean i have sql database and stored procedure which has employyes table i wanna show all employees list on a View without using any data model.
You can have your controller do the sql query, generate a List of something, then pass the list to the view using ViewData. This however is a deformation of the MVC model...
I see two solutions.. one is ugly, but it's probably what your'e looking for. In your controller you can use your procedure to get data, and then pass it to the view using ViewData collection, f.e:
public ActionResult Details(int id)
{
var intData = SPGetInt(id);
var stringData = SPGetString(id);
ViewData["intData"] = intData;
ViewData["stringData"] = stringData;
return View();
}
and then use it like:
<%=ViewData["intData"] %>
The better solution is to create at least an ViewModel, just to hold the informations you need to display. You can rewrite all data you get from DB to that model. Then you will get very important feature which is strongly typed view.

Resources