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..
2. Edit
the HaikuPartial.cshtml as shown. Split is needed here to preserve the lines of
the verses.
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.@model Haikus.Models.VERSE@{var h = Model;<p>@foreach (var s in h.CONT.Split('\r')){<label>@s</label><br />}</p>}
It would be better structure to have a public static method of VERSE of the form VERSE[] All() that returned Connect.conn.FindAll etc.@{ViewBag.Title = "Home Page";}<h2>@ViewBag.Title</h2>@foreach (var h in Haikus.Models.Connect.conn.FindAllVERSE>()) {Html.RenderPartial("HaikuPartial", h);}
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')]
5. Let’s display the author for each
haiku.
6. Rebuild Solution. Now check our page works. (The picture is a little slow to appear)@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>}
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.
@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.
9. Let’s add code to the Haiku model to add a Haiku, in VERSE.cs, after the declaration of CONT.@if (Request.IsAuthenticated){<h2>Contribute a Haiku:</h2>Html.RenderPartial("NewHaikuPartial");}
10. Finally, we need to deal with the POST of the new Haiku.public static void Add(VERSE m){Connect.conn.Post(m);}
///
/// 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.
as shown:
13. Add the following to Views/Home/Index.cshtml (a good place is before the@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>
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.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.@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 + "'/")" />}}}
15. And add a View to Views>Home called Author.public ActionResult Author(string id){ViewBag.Author = id;return View();}
Make sure this time the Template is
“Empty (without model)”
Also clear the partial view checkbox.16. And make the entries in the list of Authors into links to show this new view. Change Views/Home/Index.cshtml to contain:@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);}}
17. Try this out:foreach (var an in lt){<a href="@("/Home/Author/" + an + "/")"><img alt="@an" title="@(an + "'s haikus")"src="@("/Account/Picture/" + an + "/")" /></a>}
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.
Close the browser when you’ve done them all.
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
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.
20. Add this code inside the Shared>HaikuPartial view in place of theusing 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;}
21. We need to add these methods to the HomeController.@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 + "/")" />}
22. In Views>Home add a partial view called EditHaikuPartial,using the scaffolding for Edit and the VERSE model,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);}
And add the TextAreaFor bits shown.
Rowversion is part of Pyrrho Versioned persistence
machinery and is needed for Put.23. We need a post method for the Save in HomeController.@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>
///
/// 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.cs25. Try out the new machinery.public static void Update(VERSE m){Connect.conn.Put(m);}
Haikus should be 2 or 3 lines and
14 or 21 syllables.
Close the browser.
No comments:
Post a Comment