top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Load Views From Database In ASP.NET MVC

+5 votes
624 views

ASP.NET MVC organizes view files in the Views folder. This arrangement works fine for most of the applications. However, in some cases you may need to load views from database rather than physical disk file. Consider an example wherein you are building a portal or a content management system. You may want to allow the administrator to create or modify views and then you may want to load these views dynamically. Such dynamically created / modified views may not be a nice fit into the folder based arrangement of MVC. In such cases the recommended way is to store views in a database and load them on the fly. This article discusses how t his can be accomplished.

The Views database table

In order to load views from a database you first need to create a table (I have named it - Views) as shown below:

image

You can add the Views table in any existing database or create a database in App_Data specifically to house Views table. The Views table has four columns - Id, ViewName, ViewPath and ViewContent. The ViewName column stores a developer friendly name of a view. This name is purely for your own use and identification. The ViewPath column stores the path of a view from the root folder. For example, /Views/Home/Index.cshtml. Note that ViewPath is not a ~ qualified path. This simplifies your code that checks existence of a view (you will see that later). The ViewContent column holds the actual content of a view. This can be HTML markup and / or Razor code.

Entity Framework data model to read view data

Next, you need to have some way to read the data stored in the Views table shown above. You can write a POCO using plain ADO.NET or use EF model to do that. I my example I am using EF generated model. You also need to add a model class for the Employees table of the Northwind database. Again, this can be a POCO or EF designer generated class. I am using EF designer generated class. The two EF entities mentioned above are shown in the following figure:

image

Controller and view content

Now, add Home controller to the Controllers folder and modify its Index() action method as follows:

public ActionResult Index()
{
    NorthwindEntities db=new NorthwindEntities();
    List<Employee> model = db.Employees.ToList();
    ViewBag.Message = "This view is loaded from database!";
    return View(model);
}

The Index() action simply pulls all the Employee records into a List and passes that List to the view. It also sets Message property on the ViewBag. The Message property has been added just for the sake of testing.

Then add Index view to the project and modify it as shown below:

@model List<ViewsInDbDemo.Models.Employee>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h1>List of Employees</h1>
    <h2>@ViewBag.Message</h2>
    <table border="1" cellpadding="10">
        @foreach(var item in Model)
        {
            <tr>
                <td>@item.EmployeeID</td>
                <td>@item.FirstName</td>
                <td>@item.LastName</td>
            </tr>
        }
    </table>
</body>
</html>

The Index view is quite straightforward and simply outputs the model data (Employees) and ViewBag message (Message) to the response stream. You can run the application and see whether the view displays the Employee data and Message as expected.

Now comes the important part! Copy this whole view content and paste it into the ViewContent column of the Views table that you created earlier. And then DELETE this Index.cshtml file. That's because we want to load views from database and not from physical disk files. Also set the ViewPath column to /Views/Home/Index.cshtml.

Creating Custom VirtualPathProvider and VirtualFile

The key part of our solution is the creation of a custom VirtualPathProvider class and a VirtualFile class. A VirtualPathProvider does the job of picking the views from disk, database or any other location. In our case it will pick views from database. The views picked from database are wrapped in a custom VirtualFile so that MVC framework can further deal with it.

To create a VirtualPathProvider class, add a new class to the project as shown below:

public class BinaryIntellectVirtualPathProvider : VirtualPathProvider
{
    public override bool FileExists(string virtualPath)
    {
        var view = GetViewFromDatabase(virtualPath);

        if (view == null)
        {
            return base.FileExists(virtualPath);
        }
        else
        {
            return true;
        }
    }

    public override VirtualFile GetFile(string virtualPath)
    {
        var view = GetViewFromDatabase(virtualPath);

        if (view == null)
        {
            return base.GetFile(virtualPath);
        }
        else
        {
            byte[] content = ASCIIEncoding.ASCII.
                             GetBytes(view.ViewContent);
            return new BinaryIntellectVirtualFile
                          (virtualPath,content);
        }
    }

    public override CacheDependency GetCacheDependency
     (string virtualPath,Enumerable virtualPathDependencies, 
      DateTime utcStart)
    {

        var view = GetViewFromDatabase(virtualPath);

        if (view !=null)
        {
            return null;
        }

        return Previous.GetCacheDependency(virtualPath, 
           virtualPathDependencies, utcStart);
    }

    private View GetViewFromDatabase(string virtualPath)
    {
        virtualPath = virtualPath.Replace("~", "");

        ViewsDbEntities db = new ViewsDbEntities();
        var view = from v in db.Views
                    where v.ViewPath == virtualPath
                    select v;
        return view.SingleOrDefault();
    }
}

The BinaryIntellectVirtualPathProvider class inherits from VirtualPathProvider base class. The VirtualPathProvider class resides in System.Web.Hosting namespace. It then overrides a few methods of the base class namely FileExists() and GetFile(). There is also a helper method GetViewFromDatabase().

The GetViewFromDatabase() method retrieves a requested view from the database (Views table) and returns it to the caller. The same method can be used to determine whether a view exists in the database or not. For example, if GetViewFromDatabase() returns null it indicates that a requested view doesn't exist in the Views table.

The FileExists() overridden method checks whether a view exists in the database. If it doesn't then it calls the FileExists() of the base class, otherwise it returns true.

The GetFile() overridden method does the job of retrieving a view from the database and returning it to the caller. The method first checks whether the requested view exists in the Views table. If it doesn't then it calls the GetFile() method of the base class. If the view exists in the database it creates a new instance of  BinaryIntellectVirtualFile class (discussed shortly). The virtual path and the view content (ViewContent column) are passed to the constructor of the BinaryIntellectVirtualFile class. Notice that the view content is passed after converting it into a byte array. This is because BinaryIntellectVirtualFile class writes this content into a MemoryStream and MemortStream requires its content as byte array.

Now add a custom VirtualFile class class as shown below:

public class BinaryIntellectVirtualFile : VirtualFile
{
    private byte[] viewContent;

    public BinaryIntellectVirtualFile(string virtualPath, 
       byte[] viewContent) : base(virtualPath)
    {
        this.viewContent = viewContent;
    }

    public override Stream Open()
    {
        return new MemoryStream(viewContent);
    }
}

The BinaryIntellectVirtualFile class inherits from VirtualFile base class (System.Web.Hosting) and overrides Open() method. Notice that the constructor of BinaryIntellectVirtualFile receives view content as a byte array. The Open() method constructs a new MemoryStream based on this byte array and returns the MemoryStream to the caller.

Register the VirtualPathProvider

The final step is to register the custom VirtualPathProvider with the MVC framework. You do this in Global.asax as shown below:

protected void Application_Start()
{
  ...
  HostingEnvironment.RegisterVirtualPathProvider
    (new BinaryIntellectVirtualPathProvider());
}

To register a custom VirtualPathProvider you use HostingEnvironment class from System.Web.Hosting namespace. The RegisterVirtualPathProvider() method accepts a new instance of a VirtualPathProvider class (BinaryIntellectVirtualPathProvider in my example).

 You can run the application and see the view loaded from database in action. Here is a sample run:

image

That's it for now! Keep coding.

posted Oct 8, 2016 by Shivaranjini

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

Most of the times ASP.NET MVC views are rendered as a result of user navigating to some action. For example, when a user navigates to /home/index in the browser (either through address bar or through a hyperlink), ASP.NET MVC executes the action method and usually returns a view to the browser. This means each view is rendered as a result of a full GET or POST request. At times, however, you may want to load views dynamically through Ajax. This way you can render contents of a view without full page refresh.

Consider the following page:

image

The above page consists of a table that lists customers from the Customers table of Northwind database. Each customer row has two buttons - Customer Details and Order Details. Clicking on the respective button should display customer details and order details from the database. Without Ajax you would have submitted the page back to the server and then returned a view with the corresponding details. Using Ajax you can display the details without causing any postback to the server. This is shown below:

image

As you can see the above figure shows order details for CustomerID ALFKI above the customers table. These details are fetched via Ajax request.

While displaying data through Ajax request you have two options:

  • Fetch raw data from the server and embed it in HTML markup on the client side
  • Fetch HTML markup with data embedded from the server

Although the choice of the approach depends on a situation, it can be said that the former approach is suitable to make calls to Web API or when HTML display is dynamically decided by the client script. The later approach is suitable when ASP.NET MVC strongly typed views (or partial views) are being used to render the UI. In this example we will be using the later approach.

To develop this example, create a new ASP.NET MVC application based on the Empty template. Then add ADO.NET Entity Data Model for Customers and Orders tables of Northwind database. The Customer and Order entities are shown below:

image

Next, add HomeController and write the Index() action method as shown below:

public ActionResult Index()
{
    using (NorthwindEntities db = new NorthwindEntities())
    {
        List<Customer> model = db.Customers.ToList();
        return View(model);
    }
}

The Index() action simply retrieves all the Customer entities from the Customers DbSet and passes them to the Index view.

Now, add another action method - GetView() - to the HomeController as shown below:

public ActionResult GetView(string customerID,string viewName)
{
    object model = null;
    if(viewName=="CustomerDetails")
    {
        using(NorthwindEntities db=new NorthwindEntities())
        {
            model = db.Customers.Find(customerID);
        }
    }
    if (viewName == "OrderDetails")
    {
        using (NorthwindEntities db = new NorthwindEntities())
        {
            model = db.Orders.Where(o => o.CustomerID == customerID)
                      .OrderBy(o => o.OrderID).ToList();
        }
    }
    return PartialView(viewName,model);
}

The GetView() action method accepts two parameters - customerID and viewName. These two parameters are passed through an Ajax request. Depending on the viewName parameter either CustomerDetails partial view is returned to the caller or OrderDetails partial view is returned. These two view need model in the form of a Customer object and a List of Order entities respectively. That's why model variable is declared as object. Once model variable is populated the partial view name and the model is passed to the PartialView() method. Here, we used partial views because the HTML output is to be inserted in an existing page through Ajax.

Next, add one view (Index.cshtml) and two partial views (CustomerDetails.cshtml and OrderDetails.cshtml) to the Home sub-folder of Views folder.

Add the following markup to the CustomerDetails.cshtml partial view:

@model MVCViewsThroughAjax.Models.Customer

<table border="1" cellpadding="10">
    <tr>
        <td>Customer ID :</td>
        <td>@Model.CustomerID</td>
    </tr>
    <tr>
        <td>Company Name :</td>
        <td>@Model.CompanyName</td>
    </tr>
    <tr>
        <td>Contact Name :</td>
        <td>@Model.ContactName</td>
    </tr>
    <tr>
        <td>Country :</td>
        <td>@Model.Country</td>
    </tr>
</table>

The above markup is quite straightforward. The CustomerDetails partial view simply displays CustomerID, CompanyName, ContactName and Country of a Customer in a table.

Now add the following markup to the OrderDetails.cshtml partial page:

@model List<MVCViewsThroughAjax.Models.Order>

<table border="1" cellpadding="10">
    <tr>
        <th>Order ID</th>
        <th>Order Date</th>
        <th>Shipping Date</th>
        <th>Shipped To</th>
    </tr>
    @foreach(var item in Model)
    { 
        <tr>
            <td>@item.OrderID</td>
            <td>@item.OrderDate</td>
            <td>@item.ShippedDate</td>
            <td>@item.ShipCountry</td>
        </tr>
    }
</table>

The above markup iterates through the List of Order entities and renders a table with four columns - OrderID, OrderDate, ShippedDate and ShipCountry.

Now, add the following markup to the Index view:

@model List<MVCViewsThroughAjax.Models.Customer>

...
<html>
<head>
...
</head>
<body>
    <div id="viewPlaceHolder"></div>
    <br /><br />
    <table border="1" cellpadding="10">
        <tr>
            <th>Customer ID</th>
            <th>Company Name</th>
            <th colspan="2">Actions</th>
        </tr>
        @foreach(var item in Model)
        {
            <tr>
                <td>@item.CustomerID</td>
                <td>@item.CompanyName</td>
                <td><input type="button" class="customerDetails" 
                           value="Customer Details" /></td>
                <td><input type="button" class="orderDetails" 
                           value="Order Details" /></td>
            </tr>
        }
    </table>
</body>
</html>

The Index view receives a List of Customer entities as its model and renders a table with CustomerID, CompanyName and two buttons - Customer Details and Order Details.

Now comes the important part - making Ajax calls to display customer details and order details. Noticed the <div> at the beginning of the body section? The viewPlaceHolder is where the output of CustomerDetails.cshtml and OrderDetails.cshtml will be loaded. To do so we will use load() method of jQuery. Here is how that can be done:

$(document).ready(function () {

    $(".customerDetails").click(function (evt) {
        var cell=$(evt.target).closest("tr").children().first();
        var custID=cell.text();
        $("#viewPlaceHolder").load("/home/getview", 
            { customerID: custID, viewName: "CustomerDetails" });
    });

    $(".orderDetails").click(function (evt) {
        var cell = $(evt.target).closest("tr").children().first();
        var custID = cell.text();
        $("#viewPlaceHolder").load("/home/getview", 
           { customerID: custID, viewName: "OrderDetails" });
    });
});

Recollect that Customer Details and Order Details buttons have assigned CSS class of customerDetails and orderDetails respectively. The above jQuery code uses class selector to wire click event handlers to the respective buttons. Inside the click event handler of Customer Details button, the code retrieves the CustomerID from the table row. This is done using closest(), children() and first() methods. The CustomerID is stored in custID variable. Then load() method is called on viewPlaceHolder <div>. The first parameter of the load() method is the URL that will be requested through an Ajax request. The second parameter is a JavaScript object that supplies the data needed by the requested URL. In our example, GetView() action method needs two parameters - customerID and viewName. Hence the object has customerID and viewName properties. The customerID property is set to custID variable and viewName is set to CustomerDetails.

The click event handler of Order Details is similar but loads OrderDetails partial view.

That's it! You can now run the application and try clicking on both the buttons. The following figure shows customer details loaded successfully.

image

Notice that through out the application run the URL shown in the browser address bar remains unchanged indicating that Ajax requests are being made to display customer details and order details.

In the above example Ajax requests were made to /home/getview action. A user can also enter this URL in the browser's address bar producing undesirable results. As a precaution you can check the customerID and viewName parameters inside the GetView() action method (not shown in the above code). If these parameters are empty or contain invalid values you can throw an exception.

READ MORE

ASP.NET model binding is quite powerful and flexible. It caters to most of the scenarios without much configuration from developers. However, at times you may need to intervene in order to achieve the desired model binding effect. One such situation is when you use multiple instance of a partial view on a view. This article shows one possible approach to deal with such situations.

Suppose that you have a web page as shown below:

image

As shown in the above figure the web page captures OrderID, CustomerID, ShippingAddress and BillingAddress from the end user. This information is stored in a model class - Order - that looks like this:

public class Order
{
    public int OrderID { get; set; }
    public int CustomerID { get; set; }

    public Address ShippingAddress { get; set; }
    public Address BillingAddress { get; set; }
}

public class Address
{
    public string Street1{get;set;}
    public string Street2{get;set;}
    public string Country{get;set;}
    public string PostalCode{get;set;}
}

The Order class consists of four public properties namely OrderID, CustomerID, ShippingAddress and BillingAddress. Notice that OrderID and CustomerID are integer properties whereas ShippingAddress and BillingAddress properties are of type Address. The Address class is also shown and consists of four string properties - Street1, Street2, Country and PostalCode.

Now let's assume that the whole page is rendered using two ASP.NET MVC Partial Pages. The OrderID and CustomerID is captured using _BasicDetails.cshtml as shown below:

@model Demo.Models.Order

<table>
    <tr>
        <td>@Html.LabelFor(m=>m.OrderID)</td>
        <td>@Html.TextBoxFor(m=>m.OrderID)</td>
    </tr>
    <tr>
        <td>@Html.LabelFor(m=>m.CustomerID)</td>
        <td>@Html.TextBoxFor(m=>m.CustomerID)</td>
    </tr>
</table>

Note that _BasicDetails partial page has its model set to Order class. The partial page then uses LabelFor() and TextBoxFor() helpers to display a label and textbox for the OrderID and CustomerID model properties respectively.

The address information is captured using _Address.cshtml as shown below:

@model Demo.Models.Address

<table>
    <tr>
        <td>@Html.LabelFor(m=>m.Street1)</td>
        <td>@Html.TextBoxFor(m=>m.Street1)</td>
    </tr>
    <tr>
        <td>@Html.LabelFor(m=>m.Street2)</td>
        <td>@Html.TextBoxFor(m=>m.Street2)</td>
    </tr>
    <tr>
        <td>@Html.LabelFor(m=>m.Country)</td>
        <td>@Html.TextBoxFor(m=>m.Country)</td>
    </tr>
    <tr>
        <td>@Html.LabelFor(m=>m.PostalCode)</td>
        <td>@Html.TextBoxFor(m=>m.PostalCode)</td>
    </tr>
</table>

The _Address partial page has Address class as its model and uses LabelFor() and TextBoxFor() helpers to display model properties.

The Index view that makes use of _BasicDetails and _Address partial pages to form the complete page is shown below:

@model Demo.Models.Order

...
@using(Html.BeginForm("ProcessForm","Home",FormMethod.Post))
{
  <h3>Basic Details</h3>
  @Html.Partial("_BasicDetails")

  <h3>Shipping Address</h3>
  @Html.Partial("_Address",Model.ShippingAddress)
        
  <h3>Billing Address</h3>
  @Html.Partial("_Address",Model.BillingAddress)
        
  <input type="submit" value="Submit" />
}
</body>
</html>

The Index view renders the _BasicDetails partial page using Partial() helper. Since the model for Index view is Order class, the same is available to the _BasicDetails partial page. Then two instances of _Address partial page are rendered on the page to capture ShippingAddress and BillingAddress respectively. Recollect that _Address has Address class as its model. So, Model.ShippingAddress and Model.BillingAddress are passed to the Partial() helper.

The above form submits to ProcessForm action method that looks like this:

public ActionResult ProcessForm(Order ord)
{
    //do something with Order object here
    return View("Index");
}

And the Index() action method looks like this:

public ActionResult Index()
{
    Order ord = new Order();
    ord.BillingAddress = new Address();
    ord.ShippingAddress = new Address();
    return View(ord);
}

Both of these methods are quite straightforward and need no explanation.

Now comes the important and tricky part. If you run the application at this stage, you will get the following HTML markup in the browser (unwanted markup has been removed for the sake of clarity):

<form action="/Home/ProcessForm" method="post">        
<h3>Basic Details</h3>
<table>
    <tr>
        <td><label for="OrderID">OrderID</label></td>
        <td><input id="OrderID" name="OrderID" type="text" /></td>
    </tr>
    <tr>
        <td><label for="CustomerID">CustomerID</label></td>
        <td><input id="CustomerID" name="CustomerID" type="text" /></td>
    </tr>
</table>
<h3>Shipping Address</h3>
<table>
    <tr>
        <td><label for="Street1">Street1</label></td>
        <td><input id="Street1" name="Street1" type="text" value="" /></td>
    </tr>
    <tr>
        <td><label for="Street2">Street2</label></td>
        <td><input id="Street2" name="Street2" type="text" value="" /></td>
    </tr>
    <tr>
        <td><label for="Country">Country</label></td>
        <td><input id="Country" name="Country" type="text" value="" /></td>
    </tr>
    <tr>
        <td><label for="PostalCode">PostalCode</label></td>
        <td><input id="PostalCode" name="PostalCode" type="text" value="" /></td>
    </tr>
</table>
<h3>Billing Address</h3>
<table>
    <tr>
        <td><label for="Street1">Street1</label></td>
        <td><input id="Street1" name="Street1" type="text" value="" /></td>
    </tr>
    <tr>
        <td><label for="Street2">Street2</label></td>
        <td><input id="Street2" name="Street2" type="text" value="" /></td>
    </tr>
    <tr>
        <td><label for="Country">Country</label></td>
        <td><input id="Country" name="Country" type="text" value="" /></td>
    </tr>
    <tr>
        <td><label for="PostalCode">PostalCode</label></td>
        <td><input id="PostalCode" name="PostalCode" type="text" value="" /></td>
    </tr>
</table>
<input type="submit" value="Submit" />
</form>

Notice the markup in bold letters. Can you see HTML elements with duplicate id and name attributes? That's because you are rendering two instance of the _Address partial page. The model binding framework requires that the HTML fields follow this naming convention for the model binding to work as expected:

<input id="ShippingAddress_Street1" 
       name="ShippingAddress.Street1" type="text" value="" />
<input id="BillingAddress_Street1" 
       name="BillingAddress.Street1" type="text" value="" />

As you can see from the above markup the id and name attributes must fully quality the model property being bound. In the absence of such a naming pattern the Order instance won't be bound as expected as confirmed by the following figure:

image

As shown above the ShippingAddress and BillingAddress properties are null whereas OrderID and CustomerID are captured successfully.

The above problem can be solved by using a variation of the Partial() helper while rendering the _Address partial page. The following code shows how this is done:

<h3>Basic Details</h3>
@Html.Partial("_BasicDetails")

<h3>Shipping Address</h3>
@Html.Partial("_Address", 
  new ViewDataDictionary() 
  { 
    TemplateInfo = new TemplateInfo() 
      { HtmlFieldPrefix = "ShippingAddress" } })

<h3>Billing Address</h3>
@Html.Partial("_Address", 
  new ViewDataDictionary() 
    { TemplateInfo = new TemplateInfo() 
      { HtmlFieldPrefix = "BillingAddress" } })

The variation of Partial() helper used above uses ViewDataDictionary parameter to specify TemplateInfo. The HtmlFieldPrefix property of the TemplateInfo is set to ShippingAddress for the first instance and to the BillingAddress for the second instance.

If you run the application now, you will find the following markup in the browser:

<form action="/Home/ProcessForm" method="post">
<h3>Basic Details</h3>
<table>
    <tr>
        <td><label for="OrderID">OrderID</label></td>
        <td><input id="OrderID" name="OrderID" type="text" value="0" /></td>
    </tr>
    <tr>
        <td><label for="CustomerID">CustomerID</label></td>
        <td><input id="CustomerID" name="CustomerID" type="text" value="0" /></td>
    </tr>
</table>
<h3>Shipping Address</h3>
<table>
    <tr>
        <td><label for="ShippingAddress_Street1">Street1</label></td>
        <td><input id="ShippingAddress_Street1" 
                   name="ShippingAddress.Street1" type="text" value="" /></td>
    </tr>
    <tr>
        <td><label for="ShippingAddress_Street2">Street2</label></td>
        <td><input id="ShippingAddress_Street2" 
                   name="ShippingAddress.Street2" type="text" value="" /></td>
    </tr>
    <tr>
        <td><label for="ShippingAddress_Country">Country</label></td>
        <td><input id="ShippingAddress_Country" 
                   name="ShippingAddress.Country" type="text" value="" /></td>
    </tr>
    <tr>
        <td><label for="ShippingAddress_PostalCode">PostalCode</label></td>
        <td><input id="ShippingAddress_PostalCode" 
                   name="ShippingAddress.PostalCode" type="text" value="" /></td>
    </tr>
</table>
<h3>Billing Address</h3>
<table>
    <tr>
        <td><label for="BillingAddress_Street1">Street1</label></td>
        <td><input id="BillingAddress_Street1" 
                   name="BillingAddress.Street1" type="text" value="" /></td>
    </tr>
    <tr>
        <td><label for="BillingAddress_Street2">Street2</label></td>
        <td><input id="BillingAddress_Street2" 
                   name="BillingAddress.Street2" type="text" value="" /></td>
    </tr>
    <tr>
        <td><label for="BillingAddress_Country">Country</label></td>
        <td><input id="BillingAddress_Country" 
                   name="BillingAddress.Country" type="text" value="" /></td>
    </tr>
    <tr>
        <td><label for="BillingAddress_PostalCode">PostalCode</label></td>
        <td><input id="BillingAddress_PostalCode" 
                   name="BillingAddress.PostalCode" type="text" value="" /></td>
    </tr>
</table>
<input type="submit" value="Submit" />
</form>

As expected the id and name attributes are now fully qualified and hence the model binding will happen as expected as shown below:

image

The model binding now correctly captures ShippingAddress as well as BillingAddress information.

READ MORE

Displaying images from wellknown URLs is quite straightforward. At times, however, you need to display images that are available as raw binary data. Consider, for example, that you are building a Captcha system that generates images on the fly. These images won't reside on the server as physical files. They will be generated and held in memory using System.Drawing classes (or something similar). To display them you can't point the src attribute of an <img> element to a particular URL as such.

There can be multiple ways to deal with this problem. This article discusses a couple of them.

The first approach that I discuss involves sending a Base64 representation of the image through ViewBag. The action method under consideration generates such a Base64 version of the image (often called Data URL) and then pass it to the view via a ViewBag property. Here is how this is done:

public ActionResult Index()
{
    string path = Server.MapPath("~/images/computer.png");
    byte[] imageByteData = System.IO.File.ReadAllBytes(path);
    string imageBase64Data=Convert.ToBase64String(imageByteData);
    string imageDataURL= string.Format("data:image/png;base64,{0}", imageBase64Data);
    ViewBag.ImageData = imageDataURL;
    return View();
}

The above code shows Index() action method of HomeController. For the sake of simplicity it uses a physical image file rather than dynamically generated image. The image file is read as a byte array using ReadAllBytes() method. In a more realistic situation you will replace the first two lines with the image generation logic of your own.

Once the image content is read as a byte array, it is converted into a Base64 string using ToBase64String() method of Convert class. This Base64 string is used to form a data URL as shown. Notice how the data URL has data:image/png;base64 at the beginning. This way the browser knows that the src attribute value itself contains the image data. Make sure to change the image type (.png / .jpg / .gif etc.) as per your needs, Then a ViewBag variable named ImageData is set to this data URL.

The Index view makes use of this ViewBag property as shown below:

<img src="@ViewBag.ImageData" />

The following figure shows a sample run of the above code:

image

Let's see another technique to achieve the same result. This technique calls for creation of another action method. Instead of passing image data through a ViewBag property the src attribute of the <img> element will point to the second action method you create. Here is how this approach works:

public ActionResult GetImage()
{
    string path = Server.MapPath("~/images/computer.png");
    byte[] imageByteData = System.IO.File.ReadAllBytes(path);
    return File(imageByteData, "image/png"); 
}

Here, the GetImage() action method reads the image file into a byte array. It then uses File() method of the Controller base class to send the contents to the caller. The first parameter is a byte array that represents the file content and the second parameter indicates the MIME content type. Make sure to change the content type as per your needs.

To use the GetImage() action method you will write this markup in the view:

<img src='@Url.Action("GetImage", "Home")'/>

The src attribute of the image tag points to /Home/GetImage. If you run the application the result would be the same as in earlier case.

That's it! Keep coding!!

READ MORE

Recently while developing a sample application in ASP.NET MVC, I came across a peculiar situation. There was a LINQ to SQL class with several extensibility methods defined (OnXXXXChanging kind of methods where XXXX is the name of a property). The methods were performing some validation checks and in case of any violation were throwing exceptions. The LINQ to SQL class was working fine. However, at some places I wanted to display the validation errors (thrown by the class as exceptions) on the ASP.NET MVC views. That is where the problem began. No matter what exception you throw in the class the Validation Summary never displays the error message. This behavior is by design and is intended to hide sensitive exception details from the end user. In this specific, however, I wanted to reveal the exception message to the end user because all exceptions were basically validation errors and I was sure that they are not disclosing any sensitive system information. To overcome the problem I developed a custom action filter. The remainder of this article explains how the custom action filter works.

To understand the problem let's first reproduce the error by developing a sample LINQ to SQL class. Begin by creating a new ASP.NET MVC web application. Once created add a SQL database to it and create an Employee table in it. The schema of the Employee table is shown below:

image

Now add a new LINQ to SQL class to the web application and create the Employee LINQ to SQL class by dragging and dropping the Employees table from the Server Explorer onto the design surface of .dbml file.

image

Now, add a new class in the Models folder and modify it as shown below:

public partial class Employee
{
  partial void OnFirstNameChanging(string value)
  {
    if (value.Length < 3 || value.Length > 50)
    {
      throw new ValidationException("Invalid First Name.");
    }
  }
  partial void OnLastNameChanging(string value)
  {
    if (value.Length < 3 || value.Length > 50)
    {
      throw new ValidationException("Invalid Last Name.");
    }
  }
  ...
}

The code creates a partial class Employee and adds extensibility methods OnFirstNameChanging() and OnLastNameChanging() to it (you can add additional methods for other properties if you so wish). If there are any validation errors the methods simply throw ValidationException.

Add a controller named HomeController as shown below:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(Employee emp)
    {
        return View();
    }

}

The Index() action method simply renders the Index view. The Index view consists of three textboxes to enter FirstName, LastName and BirthDate and uses MVC Validations (see markup and screen capture below).

<% using (Html.BeginForm()) { %>
<%= Html.ValidationSummary()%>
<p>First Name :</p>
<%= Html.TextBoxFor(model => model.FirstName)%>
<%= Html.ValidationMessageFor(model => model.FirstName, "*")%>
<p>Last Name :</p>
<%= Html.TextBoxFor(model => model.LastName)%>
<%= Html.ValidationMessageFor(model => model.LastName, "*")%>
<p>Birth Date :</p>
<%= Html.TextBoxFor(model => model.BirthDate)%>
<%= Html.ValidationMessageFor(model => model.BirthDate, "*")%>
<p>
<input id="Submit1" type="submit" value="Submit" />
</p>
<%}%>

image

If you try entering invalid values in FirstName and LastName fields you will get errors as shown below:

image

Notice that though FirstName and LastName fields are showing error (*) there is no descriptive error message at all. The actual error messages ("Invalid First Name" and "Invalid Last Name") are suppressed by MVC framework for security reasons. However, since you are deliberately throwing these exceptions you know that showing them to the end user won't create any problem.

The solution is to create a custom action filter as shown below:

public class ShowExceptionDetailsInValidationSummary : FilterAttribute, IActionFilter
{
    public Type ExceptionType { get; set; }
    public string Keys { get; set; }
    public string ErrorMessage { get; set; }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        Controller c = (Controller)filterContext.Controller;
        string[] keys = null;
        Dictionary<string, string> messages = new Dictionary<string, string>();

        if (Keys != null && Keys!=string.Empty)
        {
            keys=Keys.Split(',');
        }

        if (keys == null)
        {
            foreach (string key in c.ModelState.Keys)
            {
                foreach (ModelError err in c.ModelState[key].Errors)
                {
                    if (ExceptionType != null)
                    {
                        if (err.Exception.GetType().Equals(ExceptionType))
                        {
                            if (ErrorMessage == null || ErrorMessage == string.Empty)
                            {
                                messages.Add(key, err.Exception.Message);
                            }
                            else
                            {
                                messages.Add(key, ErrorMessage);
                            }
                        }
                    }
                    else
                    {
                        if (ErrorMessage == null || ErrorMessage == string.Empty)
                        {
                            messages.Add(key, err.Exception.Message);
                        }
                        else
                        {
                            messages.Add(key, ErrorMessage);
                        }
                    }
                }
            }
        }
        else
        {
            foreach (string key in keys)
            {
                if(c.ModelState.Keys.Contains(key))
                {
                    foreach (ModelError err in c.ModelState[key].Errors)
                    {
                        if (ExceptionType != null)
                        {
                            if (err.Exception.GetType().Equals(ExceptionType))
                            {
                                if (ErrorMessage == null || ErrorMessage == string.Empty)
                                {
                                    messages.Add(key, err.Exception.Message);
                                }
                                else
                                {
                                    messages.Add(key, ErrorMessage);
                                }
                            }
                        }
                        else
                        {
                            if (ErrorMessage == null || ErrorMessage == string.Empty)
                            {
                                messages.Add(key, err.Exception.Message);
                            }
                            else
                            {
                                messages.Add(key, ErrorMessage);
                            }
                        }
                    }
                }
            }
        }

        foreach (string key in messages.Keys)
        {
            c.ModelState.AddModelError(key, messages[key]);
        }
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
    }

}

The ShowExceptionDetailsInValidationSummary action filter essentially loops through the Model Errors and then programmatically adds a model error message.

Once the ShowExceptionDetailsInValidationSummary action filter is ready you can decorate the Index() action method with it as shown below :

[HttpPost]
[ShowExceptionDetailsInValidationSummary]
public ActionResult Index(Employee emp)
{
    return View();
}

If you run the application again and try to enter invalid values for FirstName and LastName you will correctly get error messages as shown in the following figure.

image

By default ShowExceptionDetailsInValidationSummary action filter will display all the exception messages in the validation summary. You can also specify that only certain exceptions be displayed.

[ShowExceptionDetailsInValidationSummary(ExceptionType=typeof(ValidationException))]

Further you can also customize the error message and keys using ErrorMessage and Keys properties of ShowExceptionDetailsInValidationSummary class respectively.

READ MORE

At times you need to pass data from an action method belonging to one controller to an action method belonging to another controller. There are three ways to accomplish this task. They are:

  • Pass data as query string parameters
  • Pass data in TempData dictionary
  • Pass data as route parameters

 Let's quickly see how each of these three approaches work.

Pass data as query string parameters

This approach is possibly the most primitive one and involves no special consideration from your side. The action method sending the data can use Redirect() method or RedirectToAction() method to transfer the control to the receiving action method. The following code shows how this is done:

public ActionResult Index()
{
    Customer data = new Customer()
    {
        CustomerID = 1,
        CustomerName = "Abcd",
        Country = "USA"
    };
    string url=string.Format("/home2/index?customerid={0}
               &customername={1}&country={2}",
               data.CustomerID,data.CustomerName,data.Country);
    return Redirect(url);
}

The above code shows Index() action from Home1 controller. The Index action method instantiates Customer object - the model class - that looks like this:

public class Customer
{
    public int CustomerID { get; set; }
    public string CustomerName { get; set; }
    public string Country { get; set; }
}

It then forms a URL pointing to the Index() action from Home2 controller. Notice how data from Customer object is transferred in the form of query string parameters. In the above example there is no logic for generating model data but in a more realistic case you may have such a logic in this method. And once the data is generated you can pass it to the another controller using query string. The Redirect() method then takes the control to the Index() action of Home2 controller.

The Index() action of Home2 can receive the data as shown below:

public ActionResult Index()
{
    Customer data = new Customer();
    data.CustomerID = int.Parse(Request.QueryString["CustomerID"]);
    data.CustomerName = Request.QueryString["CustomerName"];
    data.Country = Request.QueryString["Country"];
    return View(data);
}

As you can see Request.QueryString collection is being used to read the values passed in the query string. Once a Customer object is formed, it is passed to the Index view.

This technique has an advantage that it is quite simple and requires no additional configuration. However, it's bit crude technique and you should avoid it if any of the other techniques can be used.

Pass data using TempData dictionary

In this technique you store the data to be passed in the TempData dictionary in the sender action method. The receiving action method reads the data from the TempData dictionary. You might be aware that TempData dictionary can hold data till it is read and this can carry data across multiple requests. The following code shows how this is done:

public ActionResult Index()
{
    Customer data = new Customer()
    {
        CustomerID = 1,
        CustomerName = "Abcd",
        Country = "USA"
    };
    TempData["mydata"] = data;
    return RedirectToAction("Index", "Home2");
}

As you can see Index() action instantiates a Customer object as before. This time, however, it stores the Customer object in a TempData key named mydata. The RedirectToAction() method is then used to take the control to the Index() action of Home2 controller.

Inside the Index() of Home2, you can read the value as follows:

public ActionResult Index()
{
    Customer data = TempData["mydata"] as Customer;
    return View(data);
}

The above code reads the Customer object from TempData dictionary and passes it to the Index view.

The TempData technique doesn't require any additional setup but it requires that session state be enabled. Also, TempData is designed to store arbitrary pieces of data. If you are planning to send model objects through TempData, that may be a deviation from standard design practices.

Pass data as route parameters

In this technique you need to do an additional work of defining a route in the system. For example, if you wish to pass the Customer data in the form of route parameters you need to define a route like this:

routes.MapRoute(
    name: "Default2",
    url: "{controller}/{action}/
          {customerid}/{customername}/{country}",
    defaults: new { controller = "Home2", action = "Index" }
);

As shown above, the route includes {customerid}, {customername}, and {country} route parameters and the route is mapped with Index() action of Home2 controller. Once the above configuration is done you can pass data from the sender action as follows:

public ActionResult Index1()
{
    Customer data = new Customer()
    {
        CustomerID = 1,
        CustomerName = "Abcd",
        Country = "USA"
    };
    return RedirectToAction("Index", "Home2", data);
}

Notice that, this time the Customer object is passed as the third parameter of RedirectToAction() method. This way Customer data will be passed in the form of route parameter values. To receive this data the receiver action method should write something like this:

public ActionResult Index()
{
    Customer data = new Customer();
    UpdateModel(data);
    return View(data);
}

// OR

public ActionResult Index(Customer data)
{
    return View(data);
}

As shown above you can either use UpdateModel() method to transfer values from the route to the Customer object or you can have a parameter to the Index() action method.

This technique is quite clean and makes use of MVC specific parts (route and route parameters). It doesn't have any dependency on session state as in the case of TempData technique. On the other hand you need to create a route to deal with the route parameters.

Note about query string and route parameters

Before I conclude this post, it would be interesting to see a small thing about how RedirectToAction() deals with query string and route parameters.

Let's assume that your sender action is like this:

public ActionResult Index()
{
    Customer data = new Customer()
    {
        CustomerID = 1,
        CustomerName = "Abcd",
        Country = "USA"
    };
    return RedirectToAction("Index", "Home2", data);
}

Notice that RedirectToAction() method passes Customer data object to Index() of Home2 as the third parameter.

The interesting thing to note is - If you haven't defined any route to match the data MVC sends it as query string. And if you have defined a route, it passes the values as route parameters. You can confirm this by observing the browser address bar once the Index() of Home2 renders the view. The following figure shows the difference:

image

That also means in the query string technique discussed earlier, you could have used exactly same code in the receiving action as in the case of route parameter technique.

In addition to the three techniques discussed above you can also use Session object but that's not discussed here separately since TempData technique anyway depends on the session storage.

That's it for now. Keep coding!

READ MORE
...