Showing posts with label Action Methods. Show all posts
Showing posts with label Action Methods. Show all posts

Sunday, July 13, 2014

Step by step how to get data via Ajax using jQuery, an Action method and a PartialView

        By Carmel Schvartzman

In this tutorial we'll learn how to get data via Ajax using jQuery, an Action method and a PartialView in Asp.Net MVC.

The data for this application will be stored in an XML file, and on clicking a button, an Ajax request will be send from the  jQuery function $.get () , to the web server. This latter will handle the HTTP-GET request inside an Action method, which in turn will respond sending the contents of a PartialView as HTML string, which will be displayed in the View as follows :




The XML file is the following:

<?xml version="1.0" encoding="utf-8" ?><notes>  <note>    <to>Fry</to>    <from>Leela</from>    <heading>Reminder</heading>    <body>Don't forget me this weekend!</body>  </note>  <note>    <to>Leela</to>    <from>Fry</from>    <heading>Finally!!!</heading>    <body>Leela, finally you accept to have a date with me!</body>  </note>  <note>    <to>Fry</to>    <from>Leela</from>    <heading>Rejection</heading>    <body>You know what? In second thoughts, i'll go out with someone else...</body>  </note></notes>

First we'll need a Controller to handle the Ajax requests, so build it with the code:

public class NotesController : Controller    {                public ActionResult Index()        {            return View();        }
Next add a View to display just a button and a placeholder for the Ajax request results :

@{    ViewBag.Title = "Index";}
<h3>Using the jQuery $.get() requesting data from an MVC Action method</h3><div class="container">    <div id="results"></div>    <button  id="btn-action">Get data from Action method via Ajax</button>

</div><script src="~/Scripts/Notes.js"></script>

Just check - and fix it if it's necessary - that you feed this View with all the proper scripts and stylesheets coming through the _Layout page :


Then add the following CSS3 , to get the style of the web page :

.container {    width: 80%;    background: #eee;    margin: 20px auto;    padding: 30px;    border: 1px solid #ccc;    border-radius: 10px;    box-shadow: 10px 10px 1px #c0c0c0;    transition: all 3s ease-out 0.5s;    text-align: center;}.note {    width: 33%;    background: #ddd;    margin: 20px auto;    padding: 30px;    border: 1px solid #eaeaea;    border-radius: 10px;    box-shadow: 10px 10px 1px #c0c0c0;    transition: all 3s ease-out 0.5s;    text-align: center;}.note:hover {    -webkit-transform: rotate(-1deg) scale(1.1,1.1);}button {    border-radius:10px;}

That will give you the proper style for the page.
Now for the script, when the button is clicked, we send an Ajax request to the web server :

$(function () {    $("button[id$=action]")      .button()      .click(function (event) {          event.preventDefault();           $.get("/Notes/GetAllNotes", null, function (res) {
              $("#results").html(res);
         
});      });});

First we code event.preventDefault() for the button to unbind any behavior like "submit" or another onclick handler that could be defined.
Then we send an HTTP-GET request to the server. Because the web server will send an text/html response, which proceeds from a PartialView template, we just insert that HTML inside a <div> using the jQuery .html() method, which in turn calls the javascript .innerHTML property of the DOM element.
On the Controller, we add the method to handle the HTTP-GET request:


public ActionResult GetAllNotes()        {            XDocument xml = XDocument.Load(Server.MapPath("~/App_Data/Notes.xml"));            return PartialView("_NotesList", xml);        }
The PartialView returned will get the XDocument as Model, and loop over the "note" elements , displaying each one inside a <div> :

@model System.Xml.Linq.XDocument
@foreach (var note in Model.Descendants("note")){        <div class="note">
        <p><b>To : </b><span>@note.Descendants("to").First().Value </span> <br />         <b>From : </b><span>@note.Descendants("from").First().Value </span> <br />       <b>Title : </b><span>@note.Descendants("heading").First().Value</span><br />     <b>Message : </b><span>@note.Descendants("body").First().Value </span></p> 
    </div>}
We just make use of the .Descendants( "" )  and the   First().Value   properties, to get the data to be displayed. Each Note node will be displayed as shown here :



The web page will show initially just the button:


And when clicked, it will display the data:




That's all!!  In this tutorial we've learned how to get data via Ajax using jQuery, an Action method and a PartialView in Asp.Net MVC.
Happy programming.....

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



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.....


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




Wednesday, March 12, 2014

Step By Step How to create an Ajax WebGrid with CRUD functionality in MVC 4 in 20 minutes

        By Carmel Schvartzman

In this tutorial we'll learn how to create an Ajax enabled WebGrid  with paging-sorting capabilities and with CRUD functionality in MVC 4 in 20 minutes. This Grid will expose data dynamically loaded from database and sent by the Action method from the web server, and will offer CRUD (Create Retrieve Update Delete) functionality. Also, the Grid will send Ajax requests for paging and sorting commands.

We'll want to create a Grid with CRUD functionality , showing as follows:



This tutorial will use data fetched from the Entity Framework, exposing the following classes:





To create the WebGrid we must create our own View, and it will not be difficult if we take advantage of the Scaffolding capacities of the MVC environment. So first let's create a new Controller called "BlogController", automatically creating the necessary Views to cope with the CRUD functionality requirements. So right click over the Controllers folder, and add a new Controller:



Name it "BlogController", and select the template "MVC Controller with read/write actions and views, using Entity Framework":



The Context to use will be of course the one you named while creating your Entity Framework Data Model, and the Model will be the Blog class, because we'll be creating, updating and deleting Blog objects.
After you create the Controller, open it and take a look at the Action Methods created for you: there are action methods for displaying the list of Blog posts (Index method), to create new ones , to update them, and to delete:




Open the Views folder and see the Views that were created for you:



First of all, let's add a link to the _Layout .cshtml file Menu, in order to browse to the Blog web page from the Home page:



Build and run without debugging(CTL-F5) your app. Then press the link "See All Posts" from the Menu:



We got a list of the posts in the shape of an HTML table. Click the Create link:




Return to the list and press the Details link:



Now do the same , and press Edit:




And now Delete:



As you see, we got all CRUD functionality. But now we want a WebGrid with paging-sorting capabilities,  instead of a table. So we'll replace the <TABLE> with an WebGrid Html Helper: open the Index View:





And comment the whole  <table> tag:



Next, we'll instantiate a WebGrid, using an overload of the extension method with the following parameters:



The final code for the WebGrid will set as its arguments the data included in the Model (an IEnumerable<>), the number of rows to display in each page, the sorting order and the columns to be displayed:




Now we display the markup of the WebGrid using the GetHtml() WebGrid method:



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


We automatically got the paging and sorting WebGrid functionalities. But we lost all CRUD functionality that was there before: deleting, editing , and so.
To get that functionality back, find the CRUD block that you comment before:

Copy - paste it to a new column on the WebGrid:



Refresh the browser to see the new column for editing:





As you can see, the Grid has not built-in style, and also the date and the pictures had not been correctly displayed. Let's add templates for displaying the data, using the "format:" argument, to display html tags correctly via the MvcHtmlString() class.
Add a new .css stylesheet file to the "Contents" folder:



Name the .css as GridStyle:




In the stylesheet we include all the style for the WebGrid, footer, header, hyperlinks, even the style for displaying adecuately the pictures:



The code (to copy-paste) is the following:
       .webgrid-table
        {
            font:italic 11px Verdana;
            width: 100%;
            display:grid;
            border-collapse: separate;
            border: solid 1px #98BF21;
            background-color: #f0c9a0;
            padding: 5px 5px 5px 5px;
        }
        .webgrid-header a
        {
            background-color: #c67f1c;
            color: #FFFFFF !important;
            font: 900 14px Verdana !important;
            padding:5px 5px 5px 5px;
            text-align: center;
        }
        .webgrid-footer, .webgrid-footer a
        {
            background-color: #c67f1c;
            color: #FFF;
            font: 900 14px Verdana;
            padding:3px 3px 3px 3px;
        }
        .webgrid-alternating-row
        {
            background-color: #e5d773;
            padding:5px 5px 5px 5px;
        }
        .title-column
        {
            font:900 13px Verdana;
            text-align:center;
        }
        .webgrid-img
        {
            width: 150px;
            height: 150px;
        }

Finally we add a <link> tag before the WebGrid, to include the .css in the Index View:


And we also add a reference to the JQuery javascript file, in order to enable the Ajax functionality:


Then, let's add the style classes to the WebGrid:



Refresh the web page, and look at the results:


Now the Grid has style, but the date and the pictures had not been correctly displayed. Let's fix that:
We added a formatted column as follows:

grid.Column("MainPicture","MainPicture", (item) =>{ return new MvcHtmlString("<img src='Images/"+  item.MainPicture +"' class='webgrid-img'></img>");})
Save and refresh the browser:




This time we got the pictures. Now for the dates:


Now the dates are well displayed. 




Notice that you can do paging:




Also the records are sorted by Title, ascending. Click on the headers of the WebGrid to sort them by date or text, or try to invert the sorting to be descending:



As you can see, i sorted the WebGrid by date descending, by clicking the DatePosted header.
But notice the flickers of the web page when you sort or you page on the grid. That's because every time you do that, the web page sends requests and refreshes the whole page.
Now we'll add Ajax support for the grid. The first thing to do is surround the webgrid with a <DIV> tag with an "ID" attribute:

Next, add the ID of the container to be refreshed with the contents of the response to an Ajax request:


Finally, refresh the web page to see that this time, when you press to the paging buttons, or when you click on the sorting headers of the webgrid, the grid is refreshed accordingly without refreshing the whole web page:



In this tutorial we've learned how to create an Ajax enabled WebGrid  with paging-sorting capabilities and with CRUD functionality in MVC 4 in 20 minutes, exposing data dynamically loaded from database and sent by the Action method from the web server.  
That's all!! 
Happy programming.....


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