Getting Started with Adobe After Effects - Part 6: Motion Blur
First Time? You can support us by signing up. It takes only 5 seconds. Click here to sign up. If you already have an account, click here to login.
Loading

1st Prize - Apple iPad


DOTNET Quiz 2011 - Sort and Filter - ASP.net MVC

  • I have a database table that holds ID, First Name, Last Name, Age and Status of a student. I need to get this data displayed in a view according to the passed parameters through the URL.

    End user types this URL http://example.com/students/list/id/active

    and the out put view must display the student data that sorted with id and filter only active students.

    Posted on 01-28-2011 00:00 |
    Fiqri Ismail
    1030 · 0% · 25

3  Answers  

Subscribe to Notifications
  • Score
    4

    This kind of URL-encoded commanding is handled my the ASP.NET MVC Routing mechanism. You specify a route that matches a URL and mark the parts or the URL that contain the options to be given to a particular command. In this case, the part Students/List/ identifies the command to be executed (i.e. display a list of students). The following two segments of the URL specify the sorting and filtering options. To code this into ASP.NET MVC (from VS2008 on), the following snipptes provide the key:

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.MapRoute("Students", "Students/List/{sort}/{status}", new { controller = "User", action = "List" }); routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Students", action = "List", id = "" });
        }
        protected void Application_Start() { RegisterRoutes(RouteTable.Routes); }
    }
    
    public class StudentsController : Controller
    {
        public ActionResult List(string sort, string status)
        {
            // check the parameters so SQL injection cannot happen
            string sql = "select ID, First Name, Last Name, Age, Status  from StudentsTable where Status = '" + status + "' order by " + id;
            // make SQL call
            // put result into dataset
            // bind dataset to grid
        }
    }
    

    The rest of the code is standard data handling / databinding code.

    Replied on Jan 31 2011 12:48AM  . 
    Guenter
    28 · 6% · 1887
  • Score
    4

    This can be done using URL Routing or ASP.NET MVC Framework. MVC Framework only will have HTML No view state, No Page Life cycle concept, No Controls in this framework. Hence its faster and more poular. Its based on MVC architecture. Controllers are responsible for responding to the requests. MVC developers like to work with pure HTML. Scripts folder comes with jQuery and we can handle ajax, jQuery validations . View and Templates renders HTML.

    The archtecure is like this. Controller responsible to take data from model and pass it to the view .HTTP Request will always go to the controller. Model brings data to the view. Model will never change. View is concerened with presentation layer. View do not perform business calculations. View is onlt for rendering UI and responsible for viewing data. View takes data from model and put it in the right path.

    Here is the code that works for the given question using MVC

    Under global.asax

    // Define the routes 
      public static void RegisterRoutes(RouteCollection routes)
            {
               routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
              routes.MapRoute("Students", "Students/List/{sort}/{status}", new { controller = "User", action = "List" }); routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Students", action = "List", id = "" });
    
            }
    
    //Register Application_Start 
    protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
    
                RegisterGlobalFilters(GlobalFilters.Filters);
                RegisterRoutes(RouteTable.Routes);
            }
    

    Create a classes called student , Student details in Model Folder Define properties for the student like id,firstname,lastname,status ,age.

     public class Student
            {
                [Required]
                public int ID { get; set; }
                public string Firstname { get; set; }
        public string Lastname { get; set; }
        public string sttus { get; set; }
        public int age {get;set;}
            }
    

    Then you need to create a student controller under controllers folder that is inherited from controllers class. Define action Results in controller class

    public ActionResult Index()
            {
                var studdetails = new StudentDetails();
                var model = rstuddetails.GetModel();
                return View(model);
            }
    

    Define necessary methods to getdata in StudentDetails

    now to view Create a view called Students under view

    For sorting the action result can be used under controller

    public class StudentController : Controller 
    { 
    
    public ActionResult List(string sort, string status)     
    { 
    
    // check the parameters so SQL injection cannot happen 
    
    string sql = "select ID, First Name, Last Name, Age, Status  from StudentsTable where Status = '" + status + "' order by " + id; 
           //or use LINQ to get the data 
    // make SQL call 
    
    // put result into dataset 
    
    // bind dataset to grid 
    
    }
    

    }

    Replied on Feb 15 2011 1:49AM  . 
    Vamshi
    134 · 1% · 376
  • Score
    8

    In general there are few ways to accomplish the task requested in the question. The "old" way of creating "human readable" urls has been to implement URL rewriting. In this case web server will inspect the incoming URL then modify it and forward request to appropriate page with appropriate parameters. URL rewriting could be done via ISAPI filters on web server or in ASP.NET layer using static rules in Web.config or dynamic rules through an HTTP module. More information on these can be found in URL Rewriting in ASP.NET, Tip/Trick: Url Rewriting with ASP.NET and A Look at ASP.NET 2.0's URL Mapping.

    However since .NET 3.5 our task can be done in easier and more convenient way. This way is URL routing. As per the question we need to implement sort and filter task in ASP.NET MVC application, so we can use .NET 3.5. Generally speaking to implement URL routing MVC is not required. A great example and detailed explanation of how to do URL routing without MVC can be found in article of Scott Mitchell Using ASP.NET Routing Without ASP.NET MVC .However implementing URL routing for MVC is probably the easiest way as .NET library already have some required code that otherwise would have to be written.

    To implement URL routing for ASP.NET MVC we need:

    1. Add a custom route to the route table. This can be done in RegisterRoutes method that is generated by the framework in Global.asax file. The order of rotes is important, so we need to make sure our route is added before the default one.
    2. Create (or make sure we already have) controller that has name [controller]Controller and method [action]. Here [controller] and [action] are items from step 1.
    3. Probably the easiest way to show the results is to create a View in folder [controller] with name [action] and instantiate it in Controller passing the model entities that have to be displayed.

    Let's see how it works. When a page request is received, it is routed to the UrlRoutingModule object and then to the MvcHandler HTTP handler. The MvcHandler HTTP handler determines which controller to invoke by adding the suffix "Controller" to the controller value in the URL to determine the type name of the controller that will handle the request. The action value in the URL determines which action method to call. There are also few things related to version of IIS; you can see it more detailed here.

    All in all the final code will look like the one below. I skipped parts of defining model and showing results

    Global.asax.cs(part of it):

    public class MvcApplication : System.Web.HttpApplication 
    { 
    public static void RegisterRoutes(RouteCollection routes) 
    { 
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
    
    //---------------------- This is a new route ---------------------- 
    routes.MapRoute( 
    "Students", // Route name 
    "Students/{action}/{sort}/{status}", // URL with parameters 
    new { controller = "Students", action = "Index", sort = UrlParameter.Optional, status = UrlParameter.Optional } // Parameter defaults 
    ); 
    //----------------------------------------------------------------- 
    
    routes.MapRoute( 
    "Default", // Route name 
    "{controller}/{action}/{id}", // URL with parameters 
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults 
    ); 
    }
    

    StudentsController.cs (part of it)

    public class StudentsController : Controller 
    { 
    public ActionResult List(string sort, string status) 
    { 
    ... 
    var students = entities.StudentSet.Where(p => p.Status == status).OrderBy(sort); 
    
    return View(students); 
    }
    

    As you can see I am using OrderBy(sort). This is not possible in standard Linq, however you can use it if you get DynamicQuery library from Microsoft samples . In this case you don't need to worry about SQL injection as DynamicQuery library will instantiate OrderBy condition based on model properties, so if invalid property name is passed in OrderBy an exception will be thrown.

    Replied on Mar 28 2011 5:15PM  . 
    Dmitry Kharlap (aka Docker)
    153 · 1% · 325

Your Answer


Sign Up or Login to post an answer.
Please note that your answer will not be considered as part of the contest because the competition is over. You can still post an answer to share your knowledge with the community.

Copyright © Rivera Informatic Private Ltd.