Showing posts with label JsonResult. Show all posts
Showing posts with label JsonResult. Show all posts

Friday, July 11, 2014

Step by step how to send all ActionResult response types in MVC 4

        By Carmel Schvartzman


In this tutorial we'll learn how to send all Action Result types in MVC 4. We'll create all types of ActionResult types in an application in Asp.Net MVC, with support for JsonResult, FileResult, RedirectResult, redirectToActionResult, EmptyResult, ContentResult, ViewResult and PartialViewResult. All of this classes inherit from the base ActionResult.

The data for this application will be an XML file, which will be displayed in a View as follows :




The documentation for the different types of ActionResult class is exposed at this MSDN web page :




We'll be rendering ALL TYPES OF ActionResult , but first let's create a new Controller, i'll call it "Blog" :





Then add a View for the "Index" Action:


Viewing this way :


Then add a new item to the Menu, for us to browse to our Controller more easily:


The Content ActionResult :


The first ActionResult will practice is the ContentResult :

 Let's render just a string :
The browser shows the rendered string:



Now let's render an entire XML file :



And the browser shows the rendered XML data:


The XML is the following, if you want to copy-paste it :
<?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>In second thoughts, i'll get out with someone else...</body>
  </note>
</notes>

The File ActionResult :

Now let's render a file :
 We'll render the same XML file as before:
 The browser shows the rendered XML:


The Redirect ActionResult :

Now let's try to REDIRECT to some web page:



We redirect the browser to my blog:



The Json ActionResult :


Now let's render JSON data:
 The browser shows the rendered JSON object:




The RedirectToAction ActionResult :


In case you need to redirect to ANOTHER ACTION method, use the RedirectToActionResult :

 The second Action method just renders the string it got from the browser.
The browser shows the redirected page, and the Action method gets and renders a "shout" argument::


But, if you wanted to use the MVC mapping for parameters (  /Blog/Echo/YourInput ), it won't work:


 That is because at the routing there is a default for requests, which states that  the parameter is called "type" and not "shout". We have to modify that behavior and set that any request send to /Blog/Echo will get an OPTIONAL "shout" argument, as follows :


Now the argument is correctly mapped:



The PartialView ActionResult :

Now let's render a PartialView, with an XML XDocument as the Model :


Add a new PartialView to the Index Action, in  addition to the View we added before:


Remark the PartialView with an "_" to remind us this is partial.
To loop through all XML nodes, we use the C# properties Descendants( "" ) and to  reach the values we use Descendants( "" ).First().Value :


And the browser displays the PartialView with the data from the XML :

 I added some CSS3 transitions and transformations to make it more responsive (see this post to deep on CSS3 transformations ) :

<style>
 
.container
{  width:20%;  background:#ffd800;  margin:20px auto;  padding:30px;  border:1px solid #eaeaea;  border-radius:10px;  box-shadow:10px 10px 1px #baa21d;  transition:all 3s ease-out 0.5s;  text-align:center; } 
.list:hover {  -webkit-transform:rotate(-1deg) scale(1.1,1.1);
}</style>


The complete example for ActionResults :

Finally, we gather together all ActionResults and render each one depending on the argument selector. First set the routing to allow the user to enter a type :


Then type all ActionResults types and switch on the actiontype parameter :



Take a look at the JSON part : we cast the XML data inside a generic List<>, to avoid an exception when the JavaScriptSerializer called by the Json object will try to serialize and found a supposed cyclic reference inside the XML :


The browser shows the XML cast as JSON :





That's all!!  In this tutorial we've learned how to send all Action Result types in MVC 4.
Happy programming.....

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


Sunday, April 27, 2014

Step by Step how to create a Cascading DropDownList with Ajax functionality

        By Carmel Shvartzman


In this tutorial we'll learn how to create two Cascading DropDownLists with Ajax functionality. The  two Cascading DropDownLists will update its items dynamically Ajax-loading data from database, according to the user's selections.

We'll design a web site using a free CSS Template, as explained in a former tutorial,  and a JQuery UI Theme that we imported in this tutorial. They are short step by step begginer's guides, so if you like the look-and-feel of this web site, follow those 10 minutes tutorials to make this same site.

We'll want to create two Cascading DropDownLists with Ajax functionality , showing as follows:

The <select> tags will be loaded with data from the following related entities:


First, create a new Controller and create a Repository instance (provided you have one):


Add a new View for the Index Action method, and create two <select> as follows:

<div class="ui-widget-content ui-corner-all divselect">
    <div class="float-left">
        Select a Blog Post
        <br />
        <select id="Posts">
            <option value="-1">Select a Post</option>
        </select>
    </div>
    <div class="float-right">
        Select a Post Comment<br />
        <select id="Comments">
            <option value="-1">Select a Comment</option>
        </select>
    </div>
    <div id="txtComment" class="ui-widget-content ui-corner-all divselect float-left"></div>
</div>

Notice we're using the JQueryUI theme CSS classes.
Now add a <script> and an Ajax $.getJSON() call which executes right after the HTML document is loaded. This call will populate the FIRST <select>  control:


<script>$(function () {
    $.getJSON("CascadingDDL/Blogs/", function (data) {
        var list = "<option value='-1'>Select a Post</option>";
        $.each(data, function (i, post) {
            list += "<option value='" + post.Value + "'>" + post.Text + "</option>";
        });
        $("#Posts").html(list);
    });

The function makes a HTTP_GET call to the following Action method, which returns all the Blog posts in JSON notation:


public ActionResult Blogs()
        {
            List<Blog> posts = Rep.RetrieveBlog(null).ToList();
            if (HttpContext.Request.IsAjaxRequest())
            {
                SelectList select = new SelectList(posts, "BlogID", "Title");
                return Json(select, JsonRequestBehavior.AllowGet);
            }
            return View(posts);
        }

This Action method uses the RetrieveBlog method on the Repository:

       public IEnumerable<Blog> RetrieveBlog(int? Id)
        {
            List<Blog> list = new List<Blog>();
            if (Id.HasValue)
            {
                list.Add(Context.Blogs.Find(Id));
            }
            else
            {
                list = Context.Blogs.ToList();
            }
            return list;
        }

It's a generic method which works with or without a parameter.
Next, add an event handler for the 1st <select> CHANGE event at the <script>:


 $("#Posts").change(function () {
        var PostId = $("#Posts > option:selected").attr("value");
        $.getJSON("CascadingDDL/Comments/" + PostId, function (data) {
            var list = "<option value='-1'>Select a Comment</option>";
            $.each(data, function (k, comment) {
                list += "<option value='" + comment.Value + "'>" + comment.Text + "</option>";
            });
            $("#Comments").html(list);
        });
    });

This sends an Ajax HTTP_GET request to populate the 2nd <select> with the data corresponding to the SELECTED value at the 1st <select> control. This $.getJSON calls another Action method :



 public ActionResult Comments(int? Id)
        {
            List<Comment> comments = Rep.RetrieveBlogComments(Id).ToList();
            if (HttpContext.Request.IsAjaxRequest())
            {
                SelectList select = new SelectList(comments, "CommentID", "Title");
                return Json(select, JsonRequestBehavior.AllowGet);
            }
            return View(comments);
        }

This method uses another Repository function as follows:

 public IEnumerable<Comment> RetrieveBlogComments(int? Id)
        {
            List<Comment> list = new List<Comment>();
            if (Id.HasValue)
            {
                list = Context.Comments.Where(c => c.BlogID == Id).ToList();
            }
            else
            {
                list = Context.Comments.ToList();
            }
            return list;
        }


This fetchs only the Comments corresponding to the selected Blog post.
Finally, append a last $.ajax HTTP_POST function to the <script>, in order to get the text of the selected Comment:

$("#Comments").change(function () {
        var Id = $("#Comments > option:selected").attr("value");
        if (Id >= 0) {
            $.ajax("CascadingDDL/CommentText/", {
                data: { "CommentId": Id }, type: "POST", success: function (txt) {
                    $("#txtComment").html("<i>" + txt + "</i>");
                }
            });
        }
    });

This $.ajax calls the following Action method:


 public JsonResult CommentText(int? CommentId)
        {
            if (HttpContext.Request.IsAjaxRequest())
            {
                string comment = Rep.RetrieveComment(CommentId).Text;
                return Json(comment);
            }
            return Json("");
        }

This Action method uses a Repository function to fetch the Comment's text::


 public Comment RetrieveComment(int? Id)
        {
            Comment comment = null;
            if (Id.HasValue)
            {
                comment = Context.Comments.Where(c => c.CommentID == Id).FirstOrDefault();
            }          
            return comment;
        }
Build and run the app:


When the user selects a Post, the list of Comments is refreshed:



And when a Comment is selected, its text is Ajax displayed below:



That's all!! 
In this tutorial we've learn how to create two Cascading DropDownLists with Ajax functionality.  

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


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