Showing posts with label Partial Views. Show all posts
Showing posts with label Partial Views. 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.....

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



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

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


Monday, May 26, 2014

Step By Step How to create partial views with Child Action Methods

        By Carmel Schvartzman

In this tutorial we'll learn how to create a partial view using Child Action Methods in MVC 4. Child Methods allow us to reuse code and markup, fully applying the DRY Software Paradigm ("Don't Repeat Yourself") , and avoiding the WET ("Write Everything Twice") approaches. The Child Actions cannot be invoked via regular user requests, instead they are invoked directly from the View. A Child Action method is to an Action method as a Partial View is to a View. 

In MVC there are 4 similar methods to render a Partial View, and it's important that we decide which one to use according to their properties:
1) The most widely used method is RenderPartial(), which is fast because it writes directly to the HTTP response stream, and is easy to use as it doesn't require to code a Child Action. But the data for the partial view must already be loaded in the view Model. The problem with this approach is, we can be tempted to manipulate the data INSIDE the PRESENTATION LAYER, to send it to the partial view. When we pass data from a view to another view we are specifying how to instantiate entity objects, and that shoud be a Bussiness Layer task.

2) Partial() is essentially the same thing but, instead RenderPartial(), it returns a string with HTML encoding, and you can use it to instantiate a variable if you like.
3) RenderAction() requires 
from the developer to code a Child Action, and therefore you could separate presentation layer from the Repository or Bussiness Layer. Is fast because it writes directly to the HTTP response stream.

4) Action() method is the same but it returns a string with HTML encoding. Using Action() you leave to the Controller (Child Action) the task of deciding which partial view to render. That way we leave to the Controller the responsability to make traffic decisions and to invoke Bussiness Logic. Also, this way we can make refactoring more neatly.
Child Actions are useful in building widgets and embedding them in the View. 

In this tutorial we'll create a Partial View and render it using an Action() call, being the presentation layer as this:



We'll display all Posts in a <TABLE> saved in a Partial View, and all Bloggers in another table from another Partial View. Each Partial View will be populated by a different Controller's Child Action.

First of all, let's create a new View inside the Shared folder at Views. This will be the "PostsList" Partial View:


 Now   for the "PostsList" Partial View, select "Blog" class for the scaffolding Model, and "List" for the template:



Open the _PostsList Partial View and take a look at the markup. It will be something like this (depending on your Entity Model):

Add the classes style definitions, CSS style that we'll add in a little bit, and look at the loop built by the template:

Notice we added the style classes to the <table> tag. Also, we've applied some formatting to properly display dates and pictures.

Now in order to display some style , 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
        {
            background-color: #c67f1c !important;
            color: #FFFFFF !important;
            font: 900 14px Verdana !important;
            padding:5px 5px 5px 5px;            
            text-align: center;
            
        }
        .details-div
        {
            background-color: #c67f1c !important;
            color: #FFFFFF !important;
            font: 900 14px Verdana !important;
            padding:5px 5px 5px 5px;
            text-align: center;
            
        }
        .ActionsTH
        {
            background-color: #c67f1c !important;
            color: #FFFFFF !important;
            font: 900 14px Verdana !important;
            padding:5px 5px 5px 5px;
            text-align: center;
            width:180px;
        }
        .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;
        }




Now open the "Index" View and invoke the Child Action using the Action() method:



Notice that we added a <link> tag , to include the .css in the Index View:



Finally, let's code the Child Method, creating first the Context in the Controller:



Now append the Child Action:
Notice that this Child Action deals directly with the data from a Repository, and also can decide whether to render some specific Partial View or another one.


Save and run the application:



That's all!! 
In this tutorial we've learn how to create a partial view using Child Action Methods in MVC 4, thus allowing us to reuse code and markup in future refactoring.  

Happy programming.....


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