A Layered ASP.NET MVC Application – Part IV

Posted: April 12, 2009 in .NET, ASP.NET, WCF
Tags: ,

Building the ASP.NET MVC Application

In the last 2 posts we have seen how to develop the Repository and WCF Services for our sample ASP.NET MVC application.This application contains the following Views:

  • Home/Index (Index.aspx) – Displaying the list of Bookmarks with options to Add New,Edit and Delete.
  • Add New (Create.aspx) – Displaying a blank form to enter the URL and Description.
  • Edit (Edit.aspx) – Displaying URL and Description of the selected bookmark.Only Description is editable.

There is a controller BookmarkController for all the above mentioned views.

Step1 – Add the Service proxy

  • Add the Service Reference from VS 2008 IDE to WCF Service
  • Instantiate and Close the proxy from BookmarkController as shown below:

     public class BookmarkController : Controller, IDisposable {
     private BookmarkServiceClient proxy = null;
     public BookmarkController()
     {
        proxy = new BookmarkServiceClient();
     }

    new public void Dispose() {
      if (proxy != null) {
            if (proxy.State != System.ServiceModel.CommunicationState.Closed) {
                proxy.Close();
            }
       }
    }

Step2 – Create Index Page

  • Create a View named Index.aspx and this should be a strongly typed view bound to IEnumerable<Bookmarks> as shown below:

          public partial class Index : ViewPage<IEnumerable<Bookmarks>> {
          }

  • The markup of this page contains a tabular view of bookmarks as shown below:

<asp:Content ID=”Content1″ ContentPlaceHolderID=”MainContent” runat=”server”>
  Bookmark List | <%= Html.ActionLink(“Add new”,”Create”,”Bookmark”) %> | <a href=”#”>Import</a>
  <br />
  <br />
  <table width=”100%”>
    <tr>

      <td width=”30%”>URL</td>
      <td width=”60%”>Description</td>
      <td>&nbsp</td>
      <td>&nbsp;</td>
    </tr>
    <% foreach (var item in ViewData.Model) {  %>
       <tr>
      <td width=”40%”><%=item.Url %></td>
      <td><%= item.Description%></td>
      <td><%= Html.ActionLink(“Edit”,”Edit”,new {id=item.BookmarkId}) %></td>
      <td><%= Html.ActionLink(“Delete”,”Delete”,new {id=item.BookmarkId}) %></td>
    </tr>
    <%} %>
  </table>
</asp:Content>

  • Add code in Controller to handle Index and Delete actions as shown below:

          public ActionResult Index() {
               ViewData[“Title”] = “Home Page”;
               ViewData[“Message”] = “Welcome to ASP.NET MVC!”;
               return View(proxy.GetBookmarkList()); //WCF Service will return a IEnumerable<Bookmarks> collection.
           }

           public ActionResult Delete(int id) {

                Bookmarks bookmark = new Bookmarks();
                bookmark.BookmarkId = id;
                bookmark.Description = string.Empty; //only id is needed to delete
                bookmark.Url = string.Empty; //only id is needed to delete
                proxy.DeleteBookmark(bookmark); //call service to delete the bookmark
                return RedirectToAction(“Index”); //Redirect To Index Page after successful deletion

          }

  • Add code in Controller to navigate to Create and Edit views as well

          public ActionResult Create() {
                 ViewData[“Title”] = “Add Bookmark”;
                  return View();
            }

         public ActionResult Edit(int id) {

              return View(proxy.GetBookmark(id));

         }

  Step2 – Create Add New Page

  • Create a strongly typed view named Create.aspx and bound to Bookmarks as shown below:

          public partial class Create : ViewPage<Bookmarks> {
          }

  • The markup contains a blank textbox and textarea for URL and Description as shown below:
<asp:Content ID=”Content1″ ContentPlaceHolderID=”MainContent” runat=”server”>
  <%= Html.ActionLink(“Home”, “Index”, “Bookmark”)%> | Add New | <a href=”#”>Import</a>
  <br />
  <h2> Add Bookmark</h2>  <%using (Html.BeginForm()) { %>
  <fieldset>
    <label>
      URL</label><br />
      <% IDictionary<string, object> attr = new Dictionary<string, object>();
         attr.Add(“style”, “width:400px”);
      %>
    <%=Html.TextBox(“Url”,””,attr) %>
    <br />
    <label>
      Description</label><br />
    <%=Html.TextArea(“Description”,””,5,50,null) %>
    <br />
    <input type=”submit” value=”Save” />
  </fieldset>
  <%} %>
</asp:Content>

 

 

 

  • Add code in Controller to save the changes when form is posted.
           [AcceptVerbs(HttpVerbs.Post)] //This attribute indicates this action method will be called only on form POST
           public ActionResult Create(string Url,string Description) {

 

 

    Step2 – Create Edit Page

  • Create a strongly typed view named Edit.aspx and bound to Bookmarks as shown below:

           public partial class Edit : ViewPage<Bookmarks> {
            }

  • The markup contains a textbox and textarea for URL and Description displaying data for selected bookmark as shown below.The Url textbox will remain disabled.

<asp:Content ID=”Content1″ ContentPlaceHolderID=”MainContent” runat=”server”>
  <%= Html.ActionLink(“Home”, “Index”, “Bookmark”)%>   |  <%= Html.ActionLink(“Add new”,”Create”,”Bookmark”) %>
  | <a href=”#”>Import</a>
  <br />
  <h2> Edit Bookmark</h2>
  <%using (Html.BeginForm()) { %>
  <fieldset>
    <label>
      URL</label><br />
    <% IDictionary<string, object> attr = new Dictionary<string, object>();
       attr.Add(“style”, “width:400px”);
       attr.Add(“disabled”, null);
    %>
    <%=Html.TextBox(“Url”,ViewData.Model.Url,attr) %>
    <br />
    <label>
      Description</label><br />
    <%=Html.TextArea(“Description”,ViewData.Model.Description,5,50,null) %>
    <br />
    <input type=”submit” value=”Save” />
  </fieldset>
  <%} %>
</asp:Content>

  • Add code in BookmarkController to save the edited changes when form is posted.

           [AcceptVerbs(HttpVerbs.Post)] //This action method will be invoked only for form POST
           public ActionResult Edit(int id,string Description) {

               Bookmarks bookmark = new Bookmarks();
               bookmark.BookmarkId = id;
               bookmark.Description = Description;
               bookmark.Url = string.Empty; //Url is not required as it is not updated
               proxy.UpdateBookmark(bookmark); //Call Service

               return RedirectToAction(“Index”); //Return to Index Page

           }

So with this our ASP.NET MVC application with a Business Entity layer exposed via WCF Service is complete.Need to check this more thoroughly and I’ll keep on posting updates and refinements on this.

Advertisements
Comments
  1. […] to VoteA Layered ASP.NET MVC Application – Part IV (4/12/2009)Sunday, April 12, 2009 from sankarsan.wordpress.comBuilding the ASP.NET MVC Application In the last […]

  2. […] Here is the original post: A Layered ASP.NET MVC Application – Part IV « Sankarsan’s Journal […]

  3. […] Original post:  A Layered ASP.NET MVC Application – Part IV « Sankarsan’s Journal […]

  4. A Layered ASP.NET MVC Application – Part IV – Sankarsan…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…

  5. sankarsan says:

    Hello zihotki ,
    Thanks for such an nice and inspiring comment.(This is called modesty which seems you do not have)
    Answer to your both questions is yes I do know a bit about of both of these I think.
    Now I have a question, what made you come to the conclusion that I am not aware of these and how it is relevant to the context of the post.
    Anyways the post series was about something else beyond the grasp of just a stylesheet hacker.

  6. […] part, he creates the repository. In the third part,  he creates the service layer. In the fourth part, he build the ASP.NET MVC application. Possibly related posts: (automatically generated)Summaries […]

  7. Danny says:

    Great stuff !

    Is the source code available for your project ?

    thanks

    • sankarsan says:

      Thanks.
      I am making some modification in the code.I will make the source code available in few days.

      • Fadi says:

        Hi Sankarsan,

        I’m trying to layer my ASP.NET MVC application as well but it’s kinda difficult to find good examples to follow.

        I was wondering if it wasn’t too much trouble to publish the code online so we can all have a look 🙂

  8. […] May 5, 2009 Posted by sankarsan in ASP.NET. Tags: ASP.NET MVC, StructureMap trackback In my last post I had completed the demo of building a layered ASP.NET MVC application(the bookmark list […]

  9. adel says:

    Hi , and it is a very interesting article , but i have a question regarding DataAnnotations and validations.
    How can we use these two (MVC 2) Techniques with such senario and especially client-Side validations.

  10. Sucharit says:

    Hi Sankarsan,

    It is really nice to see a post like this, awesome and immense helpful . FOr others Information I have worked with this great guy and though we are in a different company right now I have been closely following his blogs for last 1 year , which are crisp and to the point to help a dev . Thanks a lot for your contribution.

    Sucharit

  11. Sucharit says:

    One quick question . Do you have any idea how ASP.Net MVC + Cloud(Azure web role) + ADFS integration with WIF works . My intent is not to make my question complex but I ha ve a requirement like this.

  12. Jyoti says:

    It is really nice to see a post like this, awesome and immense helpful.
    Is the source code available for your project ?

    thanks

  13. Tom Glick says:

    Hi and thanks for this useful sample.
    I have a WCF service library with some Async calls that run full-text file searches using dtSearch and return matches…working fine in console client.

    Any reason NOT to use MVC as client for WCF service? I’m a bit confused about not finding a lot of samples of this.

    Also, is there source code for your link app? It’s quite close the optimium framework I’d like to use. Thanks.

  14. Tessa says:

    Is the source code available for download? I tried to follow along re-creating your code but got confused.

  15. Agathee says:

    Hi,

    In the BookMarkController, Delete Function having a class

    Bookmarks bookmark = new Bookmarks();

    What this “Bookmarks” refers?

    We Should Create a Model for “Bookmarks in the MVC Solution?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s