Showing posts with label ViewDataDictionary. Show all posts
Showing posts with label ViewDataDictionary. Show all posts

Monday, February 10, 2014

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

        By Carmel Schvartzman
In this tutorial we'll learn how to create a dynamic DropDownList  HTML Helper in an MVC View  in ASP.NET MVC 4. This DropDownList will expose just a few items dynamically loaded from database and sent by the Action method on 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  DropDownList 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 DropDownList 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 two Entities: Blog and Comment, with a one to many relationship between them. Open the View we just created, and type the TempData["message"] in order to display a message to the user:




Create the Form object taking care of its tags:


Also, add a button in order to submit the form:


Now, add the label which will inform the user what is the dropdownlist about:


Next, we'll add the DropDownList named "BlogPost", using an overload of the extension method with the following parameters:



The second parameter being an IEnumerable<SelectedListItem>, we'll leave it empty with a "null" value , to force the MVC framework to search the ViewBag (and therefore the ViewDataDictionary, because the ViewBag is just a wrapper of the ViewData)  for a key named "BlogPost" as the first argument tells, containing a SelectList of SelectedListItems, which soon we'll add to the Index Action method:



The third parameter is the text to display on the DropDownList , and the fourth is an anonymous object representing the CSS style:





Now for the code in the Action method, find the "Index" in the Controller, and add the code to populate the dropdownlist:



We just instantiate our Repository, and populate the SelectList with a Linq query retrieving the posts. Also, we set the Key and the Text for the SelectList, with the names of the properties we use as Key/Value, in this case, we use the "BlogID" and the "Title" properties.
Now build your application and browse to the "/NewView/Index" (or just "/NewView") web page:




We got this dropdownlist, and select the post with the Title "Sobralia Altissima" and the key "5":




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 = "BlogPost" with the value = "5":



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 Action method with the "BlogPost" parameter:



Also, we'll use the received value to send a message to the user, via the TempDataDictionary:



Because we have to load the dropdownlist again while this Action method render the View , add to the POST Action method the code to populate again the dropdownlist, this time a little more simple, fetching the data directly through the "Blog" DbSet:



Rebuild the application and select a Blog Post, pressing the Submit button:




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




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


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

Wednesday, January 22, 2014

Step By Step How to use the Label HTML Helper in an MVC 4 View

        By Carmel Schvartzman


In this tutorial we'll learn how to use the Label HTML Helper in an MVC View  in ASP.NET MVC 4
An MVC View is the responsible for rendering the html for the UI with the user: it is the Presentation level in the ModelViewController software pattern; if so , it is absolutely forbidden to include in it any bussiness logic (wich is holded into the MVC Model) or any application logic (coded inside the MVC Controllers), nor any data fetching(MVC Model responsability, sent via the Controllers).

By convention, the Views are stored inside subfolders of the View folder, named after the corresponding Controllers: then for instance, all the Views you create related to the AccountController will be placed inside the "Account" folder ("Views/Account"). The MVC framework will search a required View to be rendered, in the folder with the name of the Controller, and if it is not there, will search at the "Shared" subfolder. If you want a View to be shared among several Controllers, place it in the "Shared" folder.

A View is just a class called ViewPage: it inherits from the Page class and also implements the IViewDataContainer, in order to hold all the data sent by the Controllers inside its ViewDataDictionary.
We can also send data to the View using the ViewBag dynamic dictionary, which internally uses the ViewData dictionary to store the key/value pairs, and it is an advantage because in the ViewBag case we don't need to cast the values. There is of course the disadvantage of ViewBag being late binded and therefore we don't have compile time checking but runtime errors instead. There is another useful collection named TempDataDictionary, similar to the former, with the difference that it persists ONLY between the current request and the next request (unless you mark the key to be persisted more than that, using the Keep() method). This is useful while passing data between Action methods, or in case of errors.

We'll want to add a Label 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 first HTML Helper we'll learn about is the Label control. For the other HTML Helpers, refer to the "Categories" Menu in the top-right place in this Blog. Open the View we just created, and type the TempData["message"] in order to display a message:



Create the Form object taking care of its tags:


Also, add a button in order to submit the form:





Next, type the following code to display a TextBox:






Now build the application and run without debugging:


As you can see, we get just a textbox. We'll want also a text to be displayed on the web page, informing the user that there is a text box holding her/his name.
Our first try will be displaying a text by using the ViewBag or the ViewData collections. Therefore go to the Action method and append the following line, creating a new entry in the dictionary:



And accordingly change the View to output the text on the browser:


Now we got the text "User Name":

Let's take a look at the web page source:


Find the html that fits to the text:




As you can see, there has been rendered just a text, with no possibility of style settings or any control over the string. So this time we'll use an HTML Helper called "Label", with all its functionality. Erase the code you added to the Index Action method, and replace the ViewData["lblUserName"] for the following HTML Label control:


This Helper receives 3 arguments: the first is a string naming the control the label is linked with, in this case, the text box. The second argument is the text that the Label will display. And the third is an anonymous object specifying the label's style. We set the CSS class style as "MyLabel", and accordingly we append that class to the CSS "Site" file, in the "Contents" folder:


There we add the "MyLabel" class setting the width, font and colors of the Label Helper:




Rebuild the application, go to the browser , and refresh it:







We get the label with a custom style, and this time the page source will be as follows:



We could also set inline style as follows:




And now the page source will be as follows, although the Label appeareance will be identical:




In this tutorial we've learned how to use the most common HTML Helper,  the label control, in an MVC View in ASP.NET MVC 4, sending to it data via the ViewDataDictionary
That's all!! 
Happy programming.....


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

Tuesday, January 21, 2014

Step By Step How to use the TextBox HTML Helper in an MVC 4 View

        By Carmel Schvartzman

In this tutorial we'll learn how to use the most common HTML Helper, the TextBox control, in an MVC View in ASP.NET MVC 4. An MVC View is the responsible for rendering the html for the UI with the user: it is the Presentation level in the ModelViewController software pattern; if so , it is absolutely forbidden to include in it any bussiness logic (wich is holded into the MVC Model) or any application logic (coded inside the MVC Controllers), nor any data fetching(MVC Model responsability, sent via the Controllers).

By convention, the Views are stored inside subfolders of the View folder, named after the corresponding Controllers: then for instance, all the Views you create related to the AccountController will be placed inside the "Account" folder ("Views/Account"). The MVC framework will search a required View to be rendered, in the folder with the name of the Controller, and if it is not there, will search at the "Shared" subfolder. If you want a View to be shared among several Controllers, place it in the "Shared" folder.

A View is just a class called ViewPage: it inherits from the Page class and also implements the IViewDataContainer, in order to hold all the data sent by the Controllers inside its ViewDataDictionary.
We can also send data to the View using the ViewBag dynamic dictionary, which internally uses the ViewData dictionary to store the key/value pairs, and it is an advantage because in the ViewBag case we don't need to cast the values. There is of course the disadvantage of ViewBag being late binded and therefore we don't have compile time checking but runtime errors instead. There is another useful collection named TempDataDictionary, similar to the former, with the difference that it persists ONLY between the current request and the next request (unless you mark the key to be persisted more than that, using the Keep() method). This is useful while passing data between Action methods, or in case of errors.

In this tutorial we'll learn how to use the most common HTML Helper, the TextBox control, in an MVC View in ASP.NET MVC 4, getting the following UI results:



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 first HTML Helpers we'll learn about are the TextBox control and the Label. For the other HTML Helpers, refer to the "Categories" Menu in the top-right place in this Blog. Open the View we just created, and type the TempData["message"] in order to display a message:



Create the Form object taking care of its tags:


Also, add a button in order to submit the form:


Now, add the label which will inform the user what is the text box about. We'll send the title text from the Action method on the server side:



Next, type the following code to display a TextBox:


The first argument the TextBox Helper gets is the name of the control: this name is the one which will identify it when the request is sent to the web server. The second argument is the text that the TextBox will display before the user types something in it. Setting it as "null" forces the MVC framework to search inside the ViewDataDictionary for some key named as the control: this way we'll send the text from the Action method on the server side. The last argument is an annonimous object which contains the style of the control.

Now let's set the Action method linked to this View. Go to the "NewView" Controller and search for the Index Action method, adding to the ViewDataDictionary the values to populate the title and the textbox control:


Now build the application and run without debugging:


As you can see, we get the title and the textbox. Open the Developer's Tools ( F12 ) and refresh the web page:


You can see in the "Network" tab, that an HTTP GET request has been sent to the web server.
Enter your name, and press the submit button:



This time, an HTTP POST request has been sent by the Form. Therefore we'll handle the request by creating an Action method which processes it and uses the same View. To handle the request, add the GetVerb and the ActionName Attributes with the following arguments:



We're just instructing the MVC framework that this is the Action method that handles POST requests, and gets the input data in the "txtUserName" textbox. Notice that the name of the parameter MUST BE EXACTLY the same of the TextBox control in order to get the data. Now we'll render a message to the client side using the input data received from the browser:



Rebuild the application, go to the browser , and type your name:


We get the message telling the user that everything went OK:



In this tutorial we've learned how to use the most common HTML Helper, the TextBox control, in an MVC View in ASP.NET MVC 4, sending to it data via the ViewDataDictionary, and the TempDataDictionary
That's all!! 
Happy programming.....


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