Tuesday, 26 May 2015

ASP.NET with a REST API: Part 2

Part 1 of this exercise is here.
In this second part we demonstrate the use of ASP.NET MVC's strongly-typed views.
1. Let’s write a partial view to display a haiku. Right-click Views/Shared, select Add/View..

Give the name of the View as HaikuPartial, select Empty as the template, and for the model class select VERSE from the dropdown. Make the Data context class blank. Check Create a partial View. Click Add.
2. Edit the HaikuPartial.cshtml as shown. Split is needed here to preserve the lines of the verses.
@model Haikus.Models.VERSE
@{
    var h = Model;
       <p>
       @foreach (var s in h.CONT.Split('\r'))
       {
           <label>@s</label><br />
       }
       </p>
}
 3. Let’s make the Home/Index page show the current list of Haikus (for simplicity we suppose there aren’t too many). Delete all the current content of Views/Home>/Index.cshtml and replace by the code shown.
@{
    ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Title</h2>
@foreach (var h in Haikus.Models.Connect.conn.FindAllVERSE>())
{
       Html.RenderPartial("HaikuPartial", h);   
}
It would be better structure to have a public static method of VERSE of the form VERSE[] All() that returned Connect.conn.FindAll etc.
4.  We won’t see much unless there is at least one Haiku in the database. At the PyrrhoCmd haikus command prompt, give the command shown (or something similar).
[Insert into verse (ownr,cont) values('fred@abc.com','Cherry blossom falls like snow')]

It’s just one line for now – we will fix it later. Embedded newlines inside strings are a pain for command line tools such as PyrrhoCmd. Check this works, and close the browser.
5. Let’s display the author for each haiku.

Change the HaikuPartial.cshtml as follows:
@model Haikus.Models.VERSE
@{
    var h = Model;
    var id = h.OWNR;
    <p>
        @foreach (var s in h.CONT.Split('\r'))
       {
            <label>@s</label><br />
       }
        <img title="@id" alt="@id" src="@("/Account/Picture/'" + id + "'/")" />
    </p>
}
 6. Rebuild Solution. Now check our page works. (The picture is a little slow to appear)




Close the browser
7. Right-Click Views>Home and Add>View..  Give the name as NewHaikuPartial, select the Edit Template, select VERSE from the dropdown, leave the Data context class empty, and check the Create a Partial View checkbox.

Click Add, and edit the new page as follows:
@model Haikus.Models.VERSE

@using (Html.BeginForm("Haiku/","Home"))
{
    @Html.AntiForgeryToken()
   
    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="editor-field">
            @Html.TextAreaFor(model => model.CONT, new { rows = 3, cols = 80 })
            @Html.ValidationMessageFor(model => model.CONT)
        </div>
       <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
8. Now add this part to Home\Index.cshtml, of course the author must log in first.
   @if (Request.IsAuthenticated)
   {
       <h2>Contribute a Haiku:</h2>
       Html.RenderPartial("NewHaikuPartial");
   }
 9. Let’s add code to the Haiku model to add a Haiku, in VERSE.cs, after the declaration of CONT.
public static void Add(VERSE m)
{
  Connect.conn.Post(m);
}
10.  Finally, we need to deal with the POST of the new Haiku.

Add using Haikus.Models; at the top of HomeController.cs and this code two braces in from the end
///




/// A user has just posted a new Haiku for the collection
/// using the web form in NewHaikuPartial
///

///
///
[HttpPost]
public ActionResult Haiku(VERSE model)
{
   model.CONT = Request["CONT"]; // why is this needed?
   model.OWNR = User.Identity.Name;
   VERSE.Add(model);
   ModelState.Clear();
   return View("Index");
}
11.  Try out our new machinery: add some more authors and haikus.

The list of Authors

12. Next step is to give a list of authors to filter the haikus. Let’s create a section on the right of the page for this.

In Views>Shared>_Layout.cshtml, replace the content of
as shown:

@RenderSection("featured", required: false)
 <section class="content-wrapper main-content clear-fix">
    <section id="main" style="float:left;width:70%">
        @RenderBody()
    </section>
    <section class="right" style="float:right">
        @RenderSection("right",required:false)
     </section>
 </section>
13. Add the following to Views/Home/Index.cshtml (a good place is before the

tag.



You will also need @using Haikus.Models; at the top.
The list has just the distinct author names. We don’t want to use the Authors table in case an Author no longer has any Haikus.
@section right {
<h3>Authors</h3>
@{
   var lt = new List<string>();

   foreach (var v in Connect.conn.FindAll<VERSE>())
   {
      if (!lt.Contains(v.OWNR))
      {
         lt.Add(v.OWNR);
      }
   }
   foreach (var an in lt)
   {
     <img alt="@an" title="@an" src="@("/Account/Picture/'" + an + "'/")" />
   }
 }
}
14.  Let’s make the list of authors clickable, so that we can get to a page that just has haikus by a particular author.

Let’s add a new method to the HomeController for this.
public ActionResult Author(string id)
{
    ViewBag.Author = id;
    return View();
}
15.  And add a View to Views>Home called Author.

Make sure this time the Template is “Empty (without model)”
Also clear the partial view checkbox.
@using Haikus.Models
@{
    ViewBag.Title = "Filtered by Author";
    string id = ViewBag.Author;}
<h2>Haikus contributed by <img title="@id" alt="@id" src="@("/Account/Picture/'" + id + "'/")" /></h2>

@foreach (var h in Connect.conn.FindAll<VERSE>())
{
    if (h.OWNR == id)
    {
        Html.RenderPartial("HaikuPartial", h);
    }
}
16.  And make the entries in the list of Authors into links to show this new view. Change Views/Home/Index.cshtml to contain:
foreach (var an in lt)
{
    <a href="@("/Home/Author/" + an + "/")">
      <img alt="@an" title="@(an + "'s haikus")"
           src="@("/Account/Picture/" + an + "/")" />
    </a>
}
17.  Try this out:
18. Let’s add some icons to our database for adding editing to the site. We’ll cheat and add them as profile pictures for non-authors _Pencil etc.Right click and Save each of these as Picture: Delete, Details, Liked, NotLiked and Pencil.




a.       Register a new user called Joe@abc.com. Add Delete.jpg as Joe’s profile picture.   Have a command prompt alongside your browser window.running PyrrhoCmd haikus.     At the SQL> prompt, give the command

update author set ID ='_Delete' where ID='Joe@abc.com'
b.      Check with select ID from author

Close the browser when you’ve done them all.
19. Let’s begin by allowing an author to edit their own haiku. For convenience let’s add some stuff to VERSE.cs. Add a using clause at the top as shown, and the rest of the code shown to the VERSE class.

You can see the Delete method tidies up relationships when a haiku is deleted. (We could get the database to do this automatically.)
using System.Web.WebPages;
public static void Delete(int id)
{
    var c = Connect.conn;
    foreach (var t in c.FindWith<COMMENT>("VID="+id))
        c.Delete(t);
    foreach (var t in c.FindWith<TAGGING>("VID="+id))
        c.Delete(t);
     c.Delete(c.FindOne<VERSE>(id));
}
public bool owner(WebPageRenderingBase page)
{
   return page.Request.IsAuthenticated &&
      OWNR == page.User.Identity.Name;
}
 20. Add this code inside the Shared>HaikuPartial view in place of the
@if (h.owner(this))
{   
  <a href="@("/Home/EditHaiku/" + h.ID + "/")" >
    <img alt="Pencil" title="Edit"
        src="@("/Account/Picture/'_Pencil'/")" />
  </a>
  <a href="@("/Home/Delete/" + h.ID + "/")" >
    <img alt="Delete" title="Delete"    
        src="@("/Account/Picture/'_Delete'/")" />
  </a>
}
else
{
   <img title="@h.OWNR" alt="@h.OWNR" src="@("/Account/Picture/" + h.OWNR + "/")" />
}
 21. We need to add these methods to the HomeController.
public ActionResult Delete(int id)
{
   VERSE.Delete(id);
   return View("Index");
}

public ActionResult EditHaiku(int id)
{
    var h =  Connect.conn.FindOne<VERSE>(id);
    ViewBag.ContentsLegend = "Update your Haiku";
    return View("EditHaikuPartial",h);
}
22.  In Views>Home add a partial view called EditHaikuPartial,using the scaffolding for Edit and the VERSE model,

And add the TextAreaFor bits shown.
Rowversion is part of Pyrrho Versioned persistence machinery and is needed for Put.
@model Haikus.Models.VERSE

@{
ViewBag.Title = "EditHaiku";
    Model.CONT = Model.CONT.Replace("|", "\r\n");
}

<h2>EditHaiku</h2>

@using (Html.BeginForm("Update/", "Home"))
{
    @Html.AntiForgeryToken()
   
    <div class="form-horizontal">
        <h4>VERSE</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="editor-field">
            @Html.TextAreaFor(model => model.CONT, new { rows = 3, cols = 80 })
            @Html.ValidationMessageFor(model => model.CONT)
        </div>
        @Html.HiddenFor(model => model.ID);
        @Html.HiddenFor(model => model.rowversion);
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>
23.  We need a post method for the Save in HomeController.

I actually don’t know why we need to fetch things from Request[] ourselves here.
///



/// A user has just edited a Haiku in the collection
/// using the web form in EditHaikuPartial
///

///
///
[HttpPost]
public ActionResult Update(VERSE model)
{
    model.rowversion = long.Parse(Request["rowversion"]);
    model.ID = long.Parse(Request["ID"]);
    model.CONT = Request["CONT"];
model.OWNR = User.Identity.Name;
VERSE.Update(model);
    ModelState.Clear();
    return View("Index");
} 24. And an Update method in VERSE.cs
public static void Update(VERSE m)
{
     Connect.conn.Put(m);
}
25.  Try out the new machinery.

Haikus should be 2 or 3 lines and 14 or 21 syllables.
Close the browser.




Still to come in Part 3: Implementing Likes and Comments.

No comments:

Post a Comment