ASPHostCentral.com ASP.NET MVC Hosting BLOG

All about ASP.NET MVC 4.0 Hosting, ASP.NET MVC 3.0 Hosting and ASP.NET MVC Hosting articles

ASP.NET MVC 3 Hosting :: Using an MVC PartialView With jQuery Templates Plugin

clock November 20, 2011 14:59 by author darwin

The other day I was talking some fellow developers about web architecture techniques. I brought up the use of jQuery templates instead of another proposed technique. A case was made the template plugin was not good for progressive enhancement. The objection was it forces you to maintain two separate HTML instances to render the same content. One instance for the initial server-side rendering and one for the client-side template. I knew this was not the case, so today I will show how to execute progressive enhancement while using ASP.NET MVC partial views.

There are two things you need to leverage to make this work. First, the model you are using should only use string properties. This is a bit unorthodox, but remember in the world of Model-View-Controller or MVVM, SOA, you tend to map objects between layers so they conform to their intended use.

The Contact entity now contains only string properties:

public class Contact {

    public string FirstName {get; set; }
    public string LastName {get; set; }
    public string PhoneNumber {get; set; }
    public string Street {get; set; }
    public string City {get; set; }
    public string State {get; set; }
    public string PostalCode {get; set; }

}


I know some of you are freaking out, but calm down. You can simply transform these values to the types you actually need in you application’s natural pipeline. As for validation, not doing in this little layer. I ultimately do validation on the client for UX purposes and for real in the business layer.

Now in your controller, I am just going to use HomeController today, you need to add a new View called ContactForm. It needs to have the
ChildActionOnly attribute applied.

[ChildActionOnly]
public ActionResult ContactForm() {


    return PartialView();

}


To make this work I need to add some code and parameters. The ContactForm partial view’s primary purpose is to render the desired contact, an empty new contact or the contact merge fields for the jQuery template plugin. I have added two parameters to the controller, Id and newContact. These are used to trigger the correct Contact object values.

[ChildActionOnly]
public ActionResult ContactForm(string Id, string newContact) {
   
    if (!string.IsNullOrEmpty(Id)) {
        ViewBag.Contact = contactServiceManager.GetContact(Id); ;
    } else {

        if (string.IsNullOrEmpty(newContact)) {

            ViewBag.Contact = new Contact()
            {
                ContactId = "${ContactId}",
                FirstName = "${FirstName}",
                LastName = "${LastName}",
                Business = "${Business}",
                Address1 = "${Address1}",
                Address2 = "${Address2}",
                City = "${City}",
                State = "${State}",
                PostalCode = "${PostalCode}",
                PhoneNumber = "${PhoneNumber}",
                EMail = "${EMail}",
                Comment = "${Comment}",
            };
       
        } else {

            ViewBag.Contact = new Contact();

        }

    }
 
    return PartialView("ContactForm");
}


The controller now checks the input parameters and creates a Contact object with the desired values. If there is an Id value it tries to retrieve the contact from the business layer. If not it checks to see if an empty Contact or a merge field Contact object is needed. 

The corresponding View is pretty straight forward. It simply fills the value of each INPUT tag with the appropriate values.

<div id="ContactEditForm">
  @using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
   
<input type="hidden" name="Id" id="Id" value="@ViewBag.Contact.ContactId" />
   
<fieldset class="span-1">
     
<legend>@ViewBag.Contact.FirstName @ViewBag.Contact.LastName</legend>
     
<ul>
       
<li>
         
<label for="FirstName">
            First Name
</label><input id="FirstName" name="FirstName"
             
class="" value="@ViewBag.Contact.FirstName" /></li>
       
<li>
         
<label for="LastName">
            Last Name
</label><input id="LastName" name="LastName"
             
class="" value="@ViewBag.Contact.LastName" /></li>
       
<li>
         
<label for="Business">
            Business
</label><input id="Business" name="Business"
             
class="" value="@ViewBag.Contact.Business" /></li>
       
<li>
         
<label for="Address1">
            Address1
</label><input id="Address1" name="Address1"
             
class="" value="@ViewBag.Contact.Address1" /></li>
       
<li>
         
<label for="Address2">
            Address2
</label><input id="Address2" name="Address2"
              
class="" value="@ViewBag.Contact.Address2" /></li>
       
<li>
         
<label for="City">
            City
</label><input id="City" name="City"
             
class="" value="@ViewBag.Contact.City" /></li>
       
<li>
         
<label for="State">
            State
</label><input id="State" name="State"  
           
class="" value="@ViewBag.Contact.State" /></li>
       
<li>
         
<label for="PostalCode">
            Postal Code
</label><input id="PostalCode"
           
name="PostalCode" class="" value="@ViewBag.Contact.PostalCode" /></li>
       
<li>
         
<label for="PhoneNumber">
            Phone Number
</label><input id="PhoneNumber"
           
name="PhoneNumber" class="" value="@ViewBag.Contact.PhoneNumber" /></li>
       
<li>
         
<label for="EMail">
            E-Mail
</label><input id="EMail" name="EMail"
           
class="" value="@ViewBag.Contact.EMail" /></li>
       
<li>
         
<label for="Comment">
            Comment
</label><input id="Comment"
           
name="Comment" class="" value="@ViewBag.Contact.Comment" /></li>
       
<li>
         
<ul class="btn-List">
           
<li>
             
<button id="CancelButton" class="btn"
             
text="Cancel" type='button' tabindex="199">
                Cancel
</button>
           
</li>
           
<li>
             
<button id="SaveButton" class="btn default"
             
type='submit' tabindex="198">
                Save
</button>
           
</li>
         
</ul>
       
</li>
     
</ul>
   
</fieldset>
  }
</div>


So the way I like to do a Master List/Detail UX is to list the records in a table and display a dialog for editing purposes. But let’s say you have a user fixated on the great JavaScript scare of 1995 and has it disabled. In this scenario the edit link will not display the edit dialog, but instead take them to the edit page. 

On my Master page, the Index view in this example, the following code adds the ContactForm partial view content. It creates the jQuery Template plugin template needed to render the edit dialog.

<script id="EditFormTemplate" type="text/html">
 @{Html.RenderAction("ContactForm", new { Id = "", newContact = "" });}
 </script>


Now in the actual Edit view the following code will simply render the form in the desired format if JavaScript is turned off or someone actually does a direct link to the form.

@{Html.Action("ContactForm", new { Id = "", newContact = "" });}

Whew!!! That’s a lot to digest and we are not done! 

As far as opening the edit dialog and using the jQuery template plugin to generate the input form, the following jQuery code intercepts a click on all edit links, merges the Contact object and appends it to the dialog. If you are not familiar with the
jQueryUI dialog widget there are various examples on the web. The documentation is pretty complete as well. As for the jQuery Templates plugin you can start with the source code page and go from there. I know I really need to blog more about them and I will, I will….

$(".edit-link").click(function (e) {

  e.preventDefault();

  var jqxhr = $.ajax({
    url: GetRootUrl() + "Home/Contact?Id=" + $(this).attr("Id")
  })
            .success(function (result) {

              contact = result;

              $("#EditFormTemplate")
                        .tmpl(result)
                                .appendTo("#contactDlg");

              $("#contactDlg").dialog('open');

            })
            .error(function (qXHR, textStatus, errorThrown) {
              alert("ack! an error!\r\n" + textStatus + " " + errorThrown);
            });

});


All right, that just about does it for the core code that drives this solution. Seeing is believing. (Disclaimer, I use a pretty bad random content generator to give me some dummy data, so excuse that, it’s just placeholder to me).





New Dialog (using the same code as the Edit Dialog BTW)



Edit page, using the same ContactForm partial view.

If you are using ASP.NET WebForms you can easily translate this technique using Custom Controls (.ascx) instead of Partial Views.


So this is my quick and dirty first hack at solving a very real problem. I am sure I will improve and refine this over the coming months. Since I am just now getting into MVC I am also sure I made some faux pas with that too, but again it works and can be improved upon.

Currently rated 1.7 by 140 people

  • Currently 1.735714/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 3 Hosting :: WebGrid in ASP.Net MVC3 Razor with Entity Framework

clock November 17, 2011 15:06 by author darwin

Hello, today I will talk about WebGrid in ASP.NET MVC 3 Razor. Yesterday, I talked much about ASP.NET MVC 4 and now back to ASP.NET MVC 3 again. J

OK, let’s start it, don’t waste our time.

1. Create a new ASP.Net MVC 3 application with an empty web application. While creating the project check the radio button "UnitTest".

2. Now under the "Model" folder create two classes.



3. Now in the Blog Class copy the following code:

public class Blog
    {
       
        [Key]      
        public int BlogId { get; set; }

        [Required(ErrorMessage = "BlogName is required")]
        public string BlogName { get; set; }

        [Required(ErrorMessage = "Description is required")]
        [StringLength(120, ErrorMessage = "Description Name Not exceed more than 120 words")]
        public string Description { get; set; }
        public string Body { get; set; }

        public virtual  List<Comments > Comments_List { get; set; }

    }

See here is the validation of each property. And also hold the list of comments. That means 1 blog contains many posts. So that is a one to many relationship.

The "Virtual" keywords means it will make the relationship.

4. Now in the Comments class write the following code:

public class Comments
    {
        [Key ]
        public int CommentId { get; set; }
          public string Comment { get; set; }
        //[ForeignKey]
          public int BlogId { get; set; }
          public virtual Blog Blog { get; set; }
 
    }


See here we also have the object reference of the "blog" class. Before that I have used the virtual key word.

5. Create a "DatabaseContext" folder under the project. After that create a class named "BlogDbContext.cs" under the folder. This class is an entity class.

6. Now make a reference for the Entity Framework by clicking "Add Reference" under the project.



In my project I had already provided the dll. Without this dll the table cannot be created in the database by object class mapping.

Now paste the following code into the "BlogDbContext" class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using blogmvc3.Models;

namespace blogmvc3.DatabaseContext
{
   
public class BlogDbContext:DbContext
    {
       
public DbSet<Blog> Blog { get; set; }
       
public DbSet<Comments> Comments { get; set; }
    }
}

See here in the Dbset we are passing a blog class and a comments class. The Dbset will create a table automatically with a relation in the database.

The Namespace "System.Data.Entity" is very important for that.

7. Now we have to configure the "web.config" file for the connection string. The web.config file is under the Main Solution Project. Not the Project web.config file.



Now paste the following connection string into the web.config file.

<connectionStrings>

    <add name="BlogDBContext" connectionString="data source=.;Database=Blogdb;Trusted_Connection=true;" providerName="System.Data.SqlClient" />
  </
connectionStrings>



8. Now create a Controller Class named "HomeController" under the "ControllerFolder. After that check the "Add action for create.update,delete.." so it will automatically create the action mrthod in the Controller class.





9. Now in the "HomeController" Class first create an object of the "BlogDbContext" Class.

BlogDbContext _db = new BlogDbContext();

After that in the Index Method write the following code:

public ActionResult Index()
        {
            return View(_db.Comments .ToList ());
        }

10. Now create a master page in the Razor engine under the "shared" folder. Give it the name "_LayoutPage1.cshtml".

After that paste the following code there:

<!DOCTYPE html>

<html>
<
head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
   @* <script src="../../Scripts/jquery-ui-1.8.11.custom.min.js" type="text/javascript"></script>
    <link href="../../Content/jquery-ui-1.8.11.custom.css" rel="stylesheet" type="text/css" />
*@
</head>

<body>
    <div class="page">

        <div id="header">
            <div id="title">
                <h1>Blog Post</h1>
            </div>

            <div id="logindisplay">
                @*@Html.Partial("_LogOnPartial")*@
            </div>

            <div id="menucontainer">

                <ul id="menu">
                   @* <li>@html.actionlink("home", "index", "home")</li>*@
                    @*<li>@Html.ActionLink("About", "About", "Home")</li>*@
                   <li>@Html.ActionLink("home", "index", "home")</li>
                     <li>@Html.ActionLink("Article Post", "CreateLogin", "Article")</li>
                     @*<li>@Html.ActionLink("BookCab", "CreateLogin", "Cab")</li> *@
                </ul>

            </div>
             <script type="text/javascript"><!--                 mce: 0--></script>

        </div>

        <div id="main">
            @RenderBody()
            <div id="footer">
            </div>
        </div>
    </div>
</
body>
</
html>

11. Now go the "Home controller". Right-click the Index Method and add a view. It will look like:



Please check "Create Strongly-typed Views".

Choose Model Class "Comments" Under DropDown List.

Select "Scaffold Template" List. After that press the "Add" button. It will automatically create a view named "Index" under the "Home" folder.

12. See the Index View Engine will create code for the list view automatically.

Now delete all the code and replace it with the following code:

@model IEnumerable<blogmvc3.Models.Comments>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_LayoutPage1.cshtml";

}
@{
    var grid = new WebGrid(source: Model, canPage: true, defaultSort: "BlogName", rowsPerPage: 3, canSort: true); 
    }

<h2>Web grid</h2>
if (@Model != null ) 

 {    

  @grid.GetHtml(tableStyle:"grid",headerStyle: "head",  alternatingRowStyle: "alt",caption:"WebGrid"
           )
 
 }

<p>

    @Html.ActionLink("Create New", "Create")
</p>

Now see this code section what is written above.



See first we are creating the WebGrid and after that in the constructor parameter we are passing a different property argument such as paging property, sorting, and rows per page.

And in the second we are are calling the WebGrid by calling the "@Html.WebGrid" property. Here also we are passing a parameter for the WebGrid.

Now run the application; it will look like the following figure:



See here the BlogId and Comments are displaying in the WebGrid (marked with red). And the paging facility is also done (marked with black).

Currently rated 2.8 by 31 people

  • Currently 2.806452/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 3 Hosting :: How to Stream Files to Client in ASP.NET MVC 3

clock November 1, 2011 14:57 by author darwin

Streaming files to the client is very easy using ASP.NET MVC 3: The following code snippet shows an exemplary controller action "Download" that streams data to the client. If the client requests this action (e.g. by using the link [YOUR_CONTROLLER]/Download) the browser will (depending on it's settings) start downloading the data or open the download dialog.
The first optional parameter mimeType (e.g. "image/jpeg" for jpeg images or "application/pdf" for pdf documents) defines the HTTP header Content-type which is used by the browser to decide how to handle the data. The second optional parameter fileDownloadName defines the name of file the data should be saved to on the client's computer.

public ActionResult Download()
{
  var fileStream = [...];
  var mimeType = [...]; // optional
  var fileDownloadName = [...]; // optional
  return File(fileStream, mimeType, fileDownloadName);
}

Currently rated 2.7 by 6 people

  • Currently 2.666667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC Hosting

ASPHostCentral is a premier web hosting company where you will find low cost and reliable web hosting. We have supported the latest ASP.NET 4.5 hosting and ASP.NET MVC 4 hosting. We have supported the latest SQL Server 2012 Hosting and Windows Server 2012 Hosting too!


Sign in