Rajesh kumar’s Blog

If you have knowledge, let others light their candles at it.

Archive for August, 2011

Display HTML content through ASP.Net MVC with Razor view engine

Posted by Rajesh Kumar on August 26, 2011

In this post, I will show you how to display HTML text on web page through an ASP.Net MVC application with Razor as the View Engine. The goal is to read file content from a specified location and display on web page.

Prerequisites:

Visual Studio 2010
ASP.Net MVC3 (
http://www.asp.net/mvc/mvc3)

Let’s first create a new MVC3 project. Please follow the below steps to do so:

1. Open Visual Studio 2010.

2. Click on Create Project and select ASP.Net MVC3 template. Give any project name that you prefer and click on Next.

Image1

3. Chose the options as Intranet application. View engine as Razor. Select Html5 option.

Image2

4. Once you click on Ok, you will see the project structure as shown below:

Image3

5. When you run the application without make ANY changes, you will be able to see a home page with the welcome message.

6. Let’s wipe out default messages as we don’t need them at all. To change the application title, move to Views –> Shared folder, double click on _Layout.cshtml page to open.

7. In body section, change the “My MVC Application” to “Log Viewer application”.

8. Let’s create the model now that holds the file names list and selected file content. To do this, right click on “Model” folder, select Add –> New class option. Give the name as “LogFileModel” and select Ok button. Add the following code:

public class LogFileModel
{
    public List<SelectListItem> NamesList { get; set; }

    public string SelectedFileName { get; set; }

    [AllowHtml]
    public string SelectedFileContent { get; set; }
}

The important point to consider here is [AllowHtml]. This attribute allows us to display the HTML content.

9. For this example, let’s assume that we want to display the files information on the “Home” page itself. So, let’s go to HomeController. Please remember that ASP.Net MVC strictly follows naming conventions. The prefix of “Controller” represents the action that we are trying to perform. Here, “Home” represents, we want to display “Home” page (Index is the alias name).

10. Another important point is, ASP.Net MVC is a stateless application. It does not maintain View state. So, if we want to differentiate between normal page request and post back page request, we need to make use of other attributes such as “HttpGet” and “HttpPost”.

11. So, we want to do like this. When the page is requested freshly, we only display the list of files that are available in the specified folder. When the user selects the file and clicks on “View” button, we will get the HTML/text content from server and show on web page.

12. Let’s write the code to display list of files from selected folder as:

public class HomeController : Controller
{
   private LogFileModel _logFileModel;
   string directoryPath = @"C:\Log";

   [HttpGet]
   public ViewResult Index()
   {
        _logFileModel = new LogFileModel();
        _logFileModel.NamesList = GetLogFileNames();
            
       
// return data to View
       
return View(_logFileModel);
   }

private List<SelectListItem> GetLogFileNames()
{
    
// Get the List of files
     // Order them by last write time
   
var fileNamesQuery = fromfile in newDirectoryInfo(directoryPath).GetFiles()
                         orderby file.LastWriteTime
                         select new
SelectListItem
                        
{
                              Text = file.Name,
                              Value = file.Name,
                         };
                
     returnfileNamesQuery.ToList<SelectListItem>();
}

Here, we are trying to retrieve the list of files available in “C:\Log” folder and return to view as a list by populating it into our model class “LogFileModel” that we created earlier.

Note: Please make sure that there are some files available in Log files and is accessible to IIS users group.

13. Now, it’s the time to add dropdownlist and TextArea on web pages to hold the data.

14. Open the Index.cshtml file while is under Views –> Home folder and the following content:

@{
    ViewBag.Title = "Home Page";
}
@model LogViewer.Models.LogFileModel

<p>
   @using (Html.BeginForm())
   {
       <p>Log files: 
           @Html.DropDownListFor(x => x.SelectedFileName, Model.NamesList, "Choose the Log file")
           <input type="submit" value="View" />
       </p>
   }
   @Html.TextAreaFor(m => m.SelectedFileContent, 15, 105, new { @style = "resize: none;" }) 
</p>

15. Let’s try to understand Razor here…

ViewBag is like a Dictionary object that can be accessed and shared between View and Controller. We can pass data between these withit his.

@model LogViewer.Models.LogFileModel can be referred as a string type model binding to the view. With this, View (.cshtml) will be able to know which model it trying to speak to.

As we want to post back the page with the selected file, we need to encapsulate the HTML tags inside “form” tag. In Razor, we use it as Html.BeginForm().

@Html.DropDownListFor is used to display the list of files that are passed to View. When the user selects a file, its file name value will automatically be assigned to “SelectedFileName” property of “LogFileModel” object.

@Html.TextgAreaFor renders a “TextArea” control on web page to actually display the file content.

16. When we run our application now, you may see the UI as:

Image4

17. When you select a file and click on “View”, you will see no action. So, let’s handle that event now. To do this, go back to HomeController and add the following code:

[HttpPost]
[ValidateInput(false)]
public ViewResult Index(LogFileModel logFileModel)
{
    logFileModel.SelectedFileContent = System.IO.File.ReadAllText(Path.Combine( 
                                             directoryPath, logFileModel.SelectedFileName));
    logFileModel.NamesList = GetLogFileNames();
    return View(logFileModel);
}

18. Here, we are writing an overload method of Index that accepts our model class. We are also marking the method as [HttpPost] attribute. Another attribute [ValidateInput(false)] will stop validating the input. This allows us to display the HTML content without any problem. If this is not included, you can an error as “Potentially dangerous…”.

19. We are reassigning the FileNames list to the returning model object. We must do it as the ASP.Net MVC do not maintain ViewState.

20. That’s all. Our code is ready. Now, run the application, select the file and click on View button. You will be able to see the file content on web page.

Advertisements

Posted in ASP.Net MVC | 1 Comment »