Showing posts with label HTML Helpers. Show all posts
Showing posts with label HTML Helpers. Show all posts

Wednesday, March 26, 2014

Step By Step How to create a RadioButtonList HTML Helper loaded from Database

        By Carmel Schvartzman

In this tutorial we'll learn how to create a dynamic RadioButtonList  HTML Helper in an MVC View  in ASP.NET MVC 4. This RadioButtonList will expose just a few items dynamically loaded from database and sent by the Action method from the web server.

An Html Helper is a class designed for rendering HTML controls to the Views. It supports several extension methods representing the different controls such as forms, textboxes, labels, dropdownlists, routelinks ( "< a >" ) , actionlinks ( "< a >" ) ,textareas, passwords, listboxes, checkboxes, radiobuttons, hidden fields, editors, and validation code.

We'll want to add a  RadioButtonList to the web page, as follows:



To use the HTML Helpers we must create our own View, so first let's create a new Controller called "NewViewController", and then add a View to the Index Action method. So right click over the Controllers folder, and add a new Controller:



Name it "NewViewController", and select the template "Empty MVC Controller":


Open the Controller file and find the "Index" Action method:



Right click on it and select the option "Add View":


On the dialog, let the name be "Index", select the "ASPX" View engine, and choose a master page:

The HTML Helper we'll learn about is the RadioButtonList control. For the other HTML Helpers, refer to the "Categories" Menu in the top-right place in this Blog. We'll use the Entity Framework Data Model and the Repository we created in a previous tutorial .  The repository exposes three Entities: Feedback, Blog and Comment, these later with a one to many relationship between them.
Append to the Repository the method for fetching all Feedbacks defined in database:



Now we need a wrapper class to manage the Feedbacks, keeping track of the user's selected item. Create a UserFeedback class in the Models folder:


This class will be exposing a string property "SelectedValue" to be used by the requests to send back the ID of the selected item, and a List<Feedback> with the items from database:



Now for the code in the Action method, find the "Index" in the Controller, and add the code to populate the RadioButtonList,  sending the UserFeedback instance to the View :



Our RadioButtonList will reside inside a Form. Create the Form object taking care of its tags, and add a button in order to submit the form:


Now, add the label which will inform the user what is the RadioButtonList about. This label is a custom Html Helper created by us in a previous tutorial :



To use the custom Html Helper , in case you're using it, we need to add the "Import" directive as follows:


Also on top of the markup we define the Model this View is using: an UserFeedback object:


Inside the Form tag, type an foreach expression to display each of the feedbacks stored in the Feedbacks property of the UserFeedback instance:





Next, we'll add the RadioButtonList , using an overload of the extension method with the following parameters:



The first parameter will be an Linq expression containing the property to be rendered and to be sent back with the request, in our case, is the SelectedValue property. The second parameter will be the value of each item:



Finally, we append the name of each item using its "Description" property:


Buid (F6) and run your app (CTL-F5) , to get this presentation UI:





Now, what happens when we press the Submit button? Let's take a look at the Network tab on the Developer's Tools (F12):





An HTTP POST request has been sent to the web server, containing the Form data , the key = "SelectedValue" with the value = "2":



Therefore, we need to create a new Action Method at the "NewView" Controller to handle the HTTP POST request ( AcceptVerbs(HttpVerbs.Post) ), with the same name "Index" ( ActionName("Index") ). So add the following "GetFeedback" Action method with the "SelectedValue" parameter:





Also, we'll use the received value to send a message to the user, via the TempDataDictionary.
Now we need another View to display the results, so add a new View:





Open the View we just created, and type the TempData["message"] in order to display a message to the user. Through this message, we'll inform the user which radio button has been selected:






Rebuild the application and select a Feedback, next pressing the Submit button:




This time the user gets a message informing her/him that the selected value was 1:




In this tutorial we've learned how to create a RadioButtonList exposing items dynamically loaded from database and sent by the Action method on the web server
That's all!! 
Happy programming.....


כתב: כרמל שוורצמן




Monday, March 10, 2014

Step By Step How to make Ajax calls using PartialViews in MVC 4

        By Carmel Schvartzman


In this tutorial we'll learn how to make Ajax calls using PartialViews in MVC 4. We'll use several ActionLink Html Helpers to asynchronously render data from database, sent by some Action methods from the web server.

We'll be using three ActionLink Html Helpers.  As you know, an Html Helper is a class designed for rendering HTML controls to the Views. It supports several extension methods representing the different controls such as forms, textboxes, labels, dropdownlists, routelinks ( "< a >" ) , actionlinks ( "< a >" ) ,textareas, passwords, listboxes, checkboxes, radiobuttons, hidden fields, editors, and validation code.

We'll want to render a PartialView, via Ajax requests, showing up as follows:




The web page we're going to build, will display a list of blog posts, stored in database in a "Blog" table, and included in the Entity Framework context as follows:



By the other side, we'll need a Partial View containing a list of the posts in the Blog table. We'll make a AJAX call from the Index View, in order to populate a <div> with the contents of the PartialView. Add a new View to the "Shared" folder:

Set this as a "Partial View" , strongly typed according to the "Blog" Model class:


Because we don't need all the controls scaffolded in the View, delete the ones marked with red and retain those marked with green:


Now add the <img> tag in order to properly display the images in the page:




Now we'll build the controller to handle the user's interactions. This controller will render a simple View with a <div> placeholder in which display the Partial View, and three Ajax enabled links to call three different Action methods that filter the contents for that Partial View. Therefore, add a new Controller to the Controllers folder:


Name it "PostList", and leave it as an empty controller:




Leave the Index Action method as it is:


Now take a look again at the Model type the Partial View is expecting:



According to that, let's write another Action method to send the IEnumerable<Blog> collection to the Partial View:


The new Partial View will return a PartialViewResult with the collection obtained from a Repository we build in a previous Tutorial.

Now, for the View rendered by the Index Action method, add a new View right clicking inside the Index Action method:




Leave it as a simple View not strongly typed:


Open the Content tag and find the "Index" <F2>:


Change the title to "Posts List" and insert an Ajax.ActionLink control:


First Action Link we code, will send an GET request to the "AllPosts" Action method, and will insert the response inside the "DivPosts" update target, REPLACING its contents:



Buid (F6) and run your app (CTL-F5) , to get this presentation UI:




Click the link , and you'll see all the data ajax loaded without refreshing the web page:




Now we'll add another two Action methods to render filtered data. Notice that all we did was copy-paste the original "AllPosts" action method, adding a filter, and an HTTP POST attribute to handle POST requests:




The second Action Link we code, will send a POST request to the "Last3Posts" Action method, and will insert the response inside the "DivPosts" update target, REPLACING its contents:



Accordingly, the third Action Link we code, will send a GET request to the "AllPostsDescending" Action method, and will insert the response inside the "DivPosts".

Buid (F6) and run your app (CTL-F5) , and click the second link, to see ONLY 3 LAST posts:



Open the Developer Tools (F12) and in the NETWORK tab you'll see a POST request was sent:


And this was the response received:


You see, it's an HTML made to fit and replace the <div> tag content holder.

Now click the third link, to see all posts but SORTED descending by date posts, sending the following request:




The response received is indeed sorted descending:



And this is the ajax rendered table inside the <div> :





In this tutorial we've learned how to make Ajax calls using PartialViews in MVC 4, with several ActionLink Html Helpers used to asynchronously render filtered data from database
That's all!! 
Happy programming.....


כתב: כרמל שוורצמן