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 4 Hosting :: ASP.NET MVC 4.0 Mobile Template

clock November 16, 2011 15:22 by author darwin

Introduction

The five years back, we all are knew that  we able to developed ASP.NET mobile application usign Visual Studio, but microsoft  has been take off those templates from the visual studio in the following versions. But again there is a good news for all that Microsoft has released the much awaited ASP.NET MVC 4.0 developer preview and there are lots of features bundle with it. One of the greatest features is a mobile website. Yes, Now with ASP.NET MVC 4.0 you can create mobile site also. So let’s create a simple application and let’s see how it works.

To create mobile site first you need to click File->New Project->ASP.NET MVC 4.0 Web application. Like following.




Now once you click OK it will open a new another dialog like following where we have to choose the Mobile site.



As you can see in above post I have selected Razor view Once you click it will create a new application like following. As you can see similar structure as normal MVC Application application below.



This view are based on the standard jQuery Mobile. So this can be viewed in any tablet or mobile device. So if you have IPad and IPhone both then it will work on both. You need not to different application for both. see the browser first I have selected standard IPad size of browser.



Now lets see how it look in mobile. So I have made my browser same site as mobile. As you can see its working in both.



If you see the code of view you can see the razor syntax over there. Nothing change in razor syntax. But as you can see in below code you need to use Jquery mobile attributes like data-Role and other stuff which will convert standard HTML into mobile or device compatible website.

<ul data-role="listview" data-inset="true">
<li data-role="list-divider">Navigation</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>


That's it. It’s very easy you can create mobile compatible site in few hours. Hope you like it.

Currently rated 1.9 by 20 people

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


ASP.NET MVC 4 Hosting :: ASP.NET MVC 4 Display Modes and WURFL.NET

clock November 1, 2011 15:02 by author darwin

The usage of mobile phones to access the web is increasing day by day. So, this is now become very important for every public web application to add the support of mobile browsers. ASP.NET MVC 4 makes it very easy for you to make the mobile phone user’s browsing experience as smooth as possible. For example, with Display Modes feature, you can select views depending on the browser(mobile or desktop) capabilities. But, ASP.NET MVC 4 does not include all the information about the capabilities of different mobile or desktop devices that are currently available on the market. For example, it does not tell you about the screen resolution of various mobile or desktop devices. WURFL(Wireless Universal Resource FiLe), is an up-to-date XML configuration file which contains the information about device capabilities. It contains over 7000 unique devices and thousands of firmware variations. WURFL.NET API(the one which is created by ScientiaMobile), currently, is the only .NET standard API for accessing WURLF data. WURFL.NET API contains information about devices in a list of over 500 capabilities. In this article, I will show you how you can use ASP.NET MVC 4  Display Modes feature with WURFL.NET API.

Description:

Firstly, create a new ASP.NET MVC 4 application. Next, open the Package Manager Console and type “Install-Package WURFL_Official_API”. This will add the WURFL.NET API in the application. You can also install the package using “Add Library Package Reference” dialog. Doing this will automatically add a reference to the WURFL.dll in the application. It will also add web_browsers_patch.xml and wurfl-latest.zip data files in App_Data folder. This step will make the WURFL.NET API available to the application.  


Now you need to tell WURFL.NET API about the location of web_browsers_patch.xml and wurfl-latest.zip data files. There are three ways to do this. First way: specify these data files in the web.config file,

        <wurfl>
            <mainFile path=”C:\….\WURFL.NETAndDisplayModes\App_Data\wurfl-latest.zip” />
            <patches>
              <patch path=”C:\….\WURFL.NETAndDisplayModes\App_Data\web_browsers_patch.xml” />
            </patches>
        </wurfl>

Note, you need to specify the complete path of data files. Currently, WURFL.NET API does not support any shortcuts(like, DataDirectory or ~). Next, you need add the following code inside the global.asax.cs file,

        public const String WurflManagerCacheKey = “__WurflManager”;
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            LoadWurflData(Context.Cache);
        }
        public static void LoadWurflData(System.Web.Caching.Cache cache)
        {
            var configurer = new ApplicationConfigurer();
            var manager = WURFLManagerBuilder.Build(configurer);
            cache[WurflManagerCacheKey] = manager;
        }

Second way: instead of using web.config file, you can put all your code inside the global.asax.cs file,

        public const String WurflManagerCacheKey = “__WurflManager”;
        public const String WurflDataFilePath = “~/App_Data/wurfl-latest.zip”;
        public const String WurflPatchFilePath = “~/App_Data/web_browsers_patch.xml”;
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            LoadWurflData(Context);
        }

        public static void LoadWurflData(HttpContext context)
        {
            var server = context.Server;
            var wurflDataFile = server.MapPath(WurflDataFilePath);
            var wurflPatchFile = server.MapPath(WurflPatchFilePath);
            var configurer = new InMemoryConfigurer()
                    .MainFile(wurflDataFile)
                    .PatchFile(wurflPatchFile);
            var manager = WURFLManagerBuilder.Build(configurer);
            context.Cache[WurflManagerCacheKey] = manager;
        }

Third way is the combination of first and second way. First, you need to add these app settings in web.config file,

        <add key=”WurflDataFilePath” value=”~/App_Data/wurfl-latest.zip” />
        <add key=”WurflPatchFilePath” value=”~/App_Data/web_browsers_patch.xml” />

Next, add the following code inside the global.asax.cs file,

        public const String WurflManagerCacheKey = “__WurflManager”;
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            LoadWurflData(Context);
        }
        public static void LoadWurflData(HttpContext context)
        {
            var server = context.Server;
            var appSettings = WebConfigurationManager.AppSettings;
            var wurflDataFile = server.MapPath(appSettings["WurflDataFilePath"]);
            var wurflPatchFile = server.MapPath(appSettings["WurflPatchFilePath"]);
            var configurer = new InMemoryConfigurer()
                    .MainFile(wurflDataFile)
                    .PatchFile(wurflPatchFile);
            var manager = WURFLManagerBuilder.Build(configurer);
            context.Cache[WurflManagerCacheKey] = manager;
        }

Now, WURFL.NET API is initialized. Let’s say you need to show a particular view depending on the device screen resolution. You can do this by adding the following code in Application_Start method, 

        DisplayModes.Modes.Insert(0, new DefaultDisplayMode(“Resolution320By480″)
        {
            ContextCondition = (context =>
            {
                var manager = (context.Cache[WurflManagerCacheKey] as IWURFLManager);
                var cabablities = manager.GetDeviceForRequest(context.Request.UserAgent);
                return cabablities.GetCapability(“resolution_width”) == “320″
                    && cabablities.GetCapability(“resolution_height”) == “480″;
            }
            )
        });


Now, if you make a request which returns the Index view, then ASP.NET MVC framework will look for Index.Resolution320By480.cshtml file for devices with 320X480 resolution and Index.cshtml file for others. Similarly, you can add different display modes in your application depending upon the various capabilities of device. WURFL.NET consists information in a list of over 500 capabilities.

Summary:

Using ASP.NET MVC 4 Display Modes feature, you can select views depending on the browser capabilities. WURFL.NET API provides you a list of over 500 capabilities. Combining both of these features will help you to build an application which support vast amount of devices. In this article, I showed you how you can add WURFL.NET API in your application. I also showed you how you can use WURFL.NET API to find the device capabilities and then use these capabilities in ASP.NET MVC 4 application. Hopefully you will enjoy this article too.

Be the first to rate this post

  • Currently 0/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