How do you include .html or .asp file using razor? - asp.net-mvc-3

Is it possible to use server side include in Razor view engine to include .html or .asp file? We have an .html file and .asp files that contain website menus that are used for all of our websitse. Currently we use server side include for all of our sites so that we only need to change the mensu in one place.
I have the following code in the body of my _Layout.cshtml
<body>
<!--#include virtual="/serverside/menus/MainMenu.asp" -->
<!--#include virtual="/serverside/menus/library_menu.asp" -->
<!--#include virtual="/portfolios/serverside/menus/portfolio_buttons_head.html" -->
#RenderBody()
</body>
Instead of including the content of the file, if I do a view source, I see the literal text.
" <!--#include virtual="/serverside/menus/MainMenu.asp" -->
<!--#include virtual="/serverside/menus/library_menu.asp" -->
<!--#include virtual="/portfolios/serverside/menus/portfolio_buttons_head.html" -->"

#Html.Raw(File.ReadAllText(Server.MapPath("~/content/somefile.css")))

Try making your html page to a cshtml page and including it with:
#RenderPage("_header.cshtml")

Try implementing this HTML helper:
public static IHtmlString ServerSideInclude(this HtmlHelper helper, string serverPath)
{
var filePath = HttpContext.Current.Server.MapPath(serverPath);
// load from file
using (var streamReader = File.OpenText(filePath))
{
var markup = streamReader.ReadToEnd();
return new HtmlString(markup);
}
}
or:
public static IHtmlString ServerSideInclude(this HtmlHelper helper, string serverPath)
{
var filePath = HttpContext.Current.Server.MapPath(serverPath);
var markup = File.ReadAllText(filePath);
return new HtmlString(markup);
}

#RenderPage("PageHeader.cshtml")
<!-- your page body here -->
#RenderPage("PageFooter.cshtml")
This works just fine and can save you a lot of time.

Razor does not support server-side includes. The easiest solution would be copying the menu markup into your _Layout.cshtml page.
If you only needed to include .html files you could probably write a custom function that read the file from disk and wrote the output.
However since you also want to include .asp files (that could contain arbitrary server-side code) the above approach won't work. You would have to have a way to execute the .asp file, capture the generated output, and write it out to the response in your cshtml file.
In this case I would go with the copy+paste approach

Create a HtmlHelper extension method that gets the contents of the files:
public static class HtmlHelpers
{
public static MvcHtmlString WebPage(this HtmlHelper htmlHelper, string url)
{
return MvcHtmlString.Create(new WebClient().DownloadString(url));
}
}
Usage:
#Html.WebPage("/serverside/menus/MainMenu.asp");

Sorry guys for bit old answer but I found some way to attach asp file with razor. Of course you need to do some trick but it works! First of all I created .NET MVC 3 application.
In my _Layout.cshtml I added following line:
#Html.Partial("InsertHelper")
Then I created InsertHelper.aspx in my Shared folder with this content:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!--#include VIRTUAL="/ViewPage1.aspx"-->
ViewPage1.aspx is locaited in my root directory, and has just simple if to check whether it works:
<%
string dummy;
dummy="nz";
%>
<% if (dummy == "nz") { %>
nz indeed
<% } else { %>
not nz
<% } %>
And it works!
Razor is able to render partials with different ViewEngine, and that's why this example is working.
And one more thing: remember to not add following line in both aspx files:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
You can add it only once! Hope it helps!

I had the same issue when I tried to include an .inc file in MVC 4.
To solved this issue, I changed the suffix of the file to .cshtml and I added the following line
#RenderPage("../../Includes/global-banner_v4.cshtml")

Just do:
#Html.Partial("_SliderPartial")
while "_SliderPartial" is your "_SliderPartial.cshtml" file and your fine.

In my _Layout.cshtml I added following line:
#Html.Partial("InsertHelper")
Then I created InsertHelper.aspx in my Shared folder with this content:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!--#include VIRTUAL="/ViewPage1.aspx"-->

Why not include a section within your _Layout.cshtml page that will allow you to render sections based on what menu you want to use.
_Layout.cshtml
<!-- Some stuff. -->
#RenderSection("BannerContent")
<!-- Some other stuff -->
Then, in any page that uses that layout, you will have something like this:
#section BannerContent
{
#*Place your ASP.NET and HTML within this section to create/render your menus.*#
}

Html.Include(relativeVirtualPath) Extension Method
I wanted to include files like this for documentation purposes (putting the contents of a file in a <pre> tag).
To do this I added an HtmlHelperExtension with a method that takes a relative virtual path (doesn't have to be an absolute virtual path) and an optional boolean to indicate whether you wish to html encode the contents, which by default my method does since I'm using it primarily for showing code.
The real key to getting this code to work was using the VirtualPathUtility as well as the WebPageBase. Sample:
// Assume we are dealing with Razor as WebPageBase is the base page for razor.
// Making this assumption we can get the virtual path of the view currently
// executing (will return partial view virtual path or primary view virtual
// path just depending on what is executing).
var virtualDirectory = VirtualPathUtility.GetDirectory(
((WebPageBase)htmlHelper.ViewDataContainer).VirtualPath);
Full HtmlHelperExtension Code:
public static class HtmlHelperExtensions
{
private static readonly IEnumerable<string> IncludeFileSupportedExtensions = new String[]
{
".resource",
".cshtml",
".vbhtml",
};
public static IHtmlString IncludeFile(
this HtmlHelper htmlHelper,
string virtualFilePath,
bool htmlEncode = true)
{
var virtualDirectory = VirtualPathUtility.GetDirectory(
((WebPageBase)htmlHelper.ViewDataContainer).VirtualPath);
var fullVirtualPath = VirtualPathUtility.Combine(
virtualDirectory, virtualFilePath);
var filePath = htmlHelper.ViewContext.HttpContext.Server.MapPath(
fullVirtualPath);
if (File.Exists(filePath))
{
return GetHtmlString(File.ReadAllText(filePath), htmlEncode);
}
foreach (var includeFileExtension in IncludeFileSupportedExtensions)
{
var filePathWithExtension = filePath + includeFileExtension;
if (File.Exists(filePathWithExtension))
{
return GetHtmlString(File.ReadAllText(filePathWithExtension), htmlEncode);
}
}
throw new ArgumentException(string.Format(
#"Could not find path for ""{0}"".
Virtual Directory: ""{1}""
Full Virtual Path: ""{2}""
File Path: ""{3}""",
virtualFilePath, virtualDirectory, fullVirtualPath, filePath));
}
private static IHtmlString GetHtmlString(string str, bool htmlEncode)
{
return htmlEncode
? new HtmlString(HttpUtility.HtmlEncode(str))
: new HtmlString(str);
}
}

you can include server side code and aspx file in .cshtml files as below and then inlude classic asp files or html files.
Here are the steps
Index.cshtml
#Html.RenderPartial("InsertASPCodeHelper")
2.InsertASPCodeHelper.aspx
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!--#include VIRTUAL="~/Views/Shared/Header.aspx"-->
Header.aspx
<!--#include file="/header/header.inc"-->

Using includes is not the correct way to use menus with mvc. You should be using a shared layout and/or partial views.
However if for some odd reason, you must include an html file, here is a way to do it.
Helpers/HtmlHelperExtensions.cs
using System.Web;
using System.Web.Mvc;
using System.Net;
namespace MvcHtmlHelpers
{
public static class HtmlHelperExtensions
{
public static MvcHtmlString WebPage(this HtmlHelper htmlHelper, string serverPath)
{
var filePath = HttpContext.Current.Server.MapPath(serverPath);
return MvcHtmlString.Create(new WebClient().DownloadString(filePath));
}
}
}
Add new namespace to web.config
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="MvcHtmlHelpers"/>
</namespaces>
</pages>
Usage:
#Html.WebPage("/Content/pages/home.html")

Related

ASP.NET MVC3 HtmlHelper extension method like BeginForm that uses a partial view?

I created an extension method based on this answer to the SO question c# - How can I create a Html Helper like Html.BeginForm - Stack Overflow and it works fine.
Can I move the embedded HTML in the extension method into a partial view and use that partial view in the method while preserving it's current behavior? In particular, I want to be able to 'wrap' a block of arbitrary HTML.
I ask not out of any pressing need, but simply out of a desire to maintain HTML consistently, e.g. as views and partial views. I imagine it will be a lot easier to spot any problems with the HTML if it's in a view or partial view too.
Here's the HtmlHelper extension method:
public static IDisposable HelpTextMessage(this HtmlHelper helper, bool isHidden, string heading)
{
TextWriter writer = helper.ViewContext.Writer;
writer.WriteLine(
String.Format(
"<div class=\"help-text {0}\">",
isHidden ? "help-text-hidden" : ""));
writer.WriteLine(
String.Format(
"<div class=\"help-text-heading\">{0}</div>",
heading));
writer.Write("<div class=\"help-text-body\">");
return new HelpTextMessageContainer(writer);
}
Here's the HelpTextMessageContainer class:
private class HelpTextMessageContainer : IDisposable
{
private readonly TextWriter _writer;
public HelpTextMessageContainer(TextWriter writer)
{
_writer = writer;
}
public void Dispose()
{
_writer.Write("</div></div>");
}
}
In a view, I can use the extension method like this:
#using(Html.HelpTextMessage(Model.HelpText.IsHelpTextHidden(Model.SomeHelpMessage), "Something"))
{
#:To do something, first do something-more-specific, then do another-something-more-specific.
}
Or I could use it like this too:
#using(Html.HelpTextMessage(Model.HelpText.IsHelpTextHidden(Model.SomeHelpMessage), "Something"))
{
<p>To do something, first do something-more-specific, then do another-something-more-specific.</p>
<p>Also, keep in mind that you might need to do something-else-entirely if blah-blah-blah.</p>
}
I haven't found any way to move the "embedded HTML" into a partial view exactly, but a slightly more-friendly way to encapsulate the HTML in a way that provides HTML and Razor syntax highlighting and Intellisense is to move into a view helper function in a file under the app App_Code folder as described in this post on "Hugo Bonacci's Blog".
Here's my helper function:
#helper HelpTextMessage(bool isHidden, string heading, Func<object, object> content)
{
<div class="help-text #(isHidden ? "help-text-hidden" : "")">
<div class="help-text-heading">
#heading
</div>
<div class="help-text-body">
#content(null)
</div>
</div>
}
Assuming the above helper function is in a file named ViewHelpers.cshtml in the App_Code folder, it can be called in a view like this:
#ViewHelpers.HelpTextMessage(false, "Something",
#:To do something, first do something-more-specific, then do another-something-more-specific.
)
or this:
#ViewHelpers.HelpTextMessage(false, "Something",
<p>To do something, first do something-more-specific, then do another-something-more-specific.</p>
<p>Also, keep in mind that you might need to do something-else-entirely if blah-blah-blah.</p>
)
I like having the embedded HTML in a view more than I do being able to use the #using(Html.HelpTextMessage(...){ ... } syntax, so I'm pretty happy with this as a solution.

System.Web.Mvc.HtmlHelper' does not contain a definition for 'ActionLink'

I would like to use custom #Html.ActionLink
I am trying to use the following code:-
public static class LinkExtensions
{
public static MvcHtmlString MyActionLink(
this HtmlHelper htmlHelper,
string linkText,
string action,
string controller)
{
var currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
var currentController = mlHelper.ViewContext.RouteData.GetRequiredString("controller");
if (action == currentAction && controller == currentController)
{
var anchor = new TagBuilder("a");
anchor.Attributes["href"] = "#";
anchor.AddCssClass("currentPageCSS");
anchor.SetInnerText(linkText);
return MvcHtmlString.Create(anchor.ToString());
}
return htmlHelper.ActionLink(linkText, action, controller);
}
}
From Custom ActionLink helper that knows what page you're on
But I am getting
System.Web.Mvc.HtmlHelper' does not contain a definition for
'ActionLink' and no extension method 'ActionLink' accepting a first
argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you
missing a using directive or an assembly reference?
Add this using System.Web.Mvc.Html; on top of your file
Make sure you have the namespace for your extensions class included in your web.config. For example:
namespace MyProject.Extensions
{
public static class LinkExtensions
{
//code
}
}
In your site Web.config and/or Web.config located in your "Views" folder:
<system.web>
<pages>
<namespaces>
<add namespace="MyProject.Extensions" />
</namespaces>
</pages>
</system.web>
Otherwise include a "using" block for the namespace at the top of your view page can work but for common namespaces I would do the above.
ASPX:
<%# Import namespace="MyProject.Extensions" %>
RAZOR:
#using MyProject.Extensions
Don't forget that the first parameter only accepts string. It will show you this error if it's NOT.
Make sure that you have following using in your class file:
using System.Web.Mvc.Html;
This is needed because the HtmlHelper class is located in System.Web.Mvc namespace but the ActionLink extension method is located in System.Web.Mvc.Html namespace.
If your using nopcommerce add this using statement at the top of your view file.
#using Nop.Web.Framework.UI
My issue was, I had incomplete syntax, "#Html.actionLink", in a view. Looks like I had started to add an action link and went a different direction but forgot to remove the partial action link, this caused the same error as above.... So check your syntax as that will throw the same runtime error. Good luck!

Performance bottleneck Url.Action - can I workaround it?

I have an application that I recently upgraded from ASP.NET MVC1 to ASP.NET MVC4 rc1.
It uses the Webforms viewengine.
It has performance issues whenever Url.Action(action,controller) is used.
I can reproduce the issue in ASP.NET MVC3.
I need 3ms to render views that have 10 instances of the Url.Action helper in it in ASP.NET MVC1 and 40ms to render the same in ASP.NET MVC3.
I already found some ways to make it render faster:
I moved the default route to the top
I removed Url.Action and used static links
This does not feel right: the application is pretty large and I need the goodness of a decent working routing in it. I am also not confident that I found all performance bottlenecks. Routing is a central part of MVC: if there is something performing badly it will pop up in different parts of the application.
I have the impression that MVC3 introduced some routing features (like regex constraints) that even if I dont use them lead to a badly performing application.
Is there something I can do like turning of features of routing or using a different set of URL-helpers?
This code reproduces the issue:
Index action
public ActionResult Index()
{
return View();
}
index.aspx
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head >
<title></title>
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="page">
<%= Url.Action("Action1", "Controller1") %>
<%= Url.Action("Action2", "Controller2") %>
<%= Url.Action("Action3", "Controller3") %>
<%= Url.Action("Action4", "Controller4") %>
<%= Url.Action("Action5", "Controller5") %>
<%= Url.Action("Action6", "Controller6") %>
<%= Url.Action("Action7", "Controller7") %>
<%= Url.Action("Action8", "Controller8") %>
<%= Url.Action("Action9", "Controller9") %>
<%= Url.Action("Action10", "Controller10") %>
</div>
</body>
</html>
Route registration
This looks strange: but I just want to simulate my not very complicated routing. This is not the 600 routes of SO!
public static void RegisterRoutesSlow(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{language}/Content/{*pathInfo}");
routes.IgnoreRoute("images/{*pathinfo}");
routes.IgnoreRoute("scripts/{*pathinfo}");
routes.IgnoreRoute("content/{*pathinfo}");
routes.IgnoreRoute("{file}.gif");
routes.IgnoreRoute("{file}.jpg");
routes.IgnoreRoute("{file}.js");
routes.IgnoreRoute("{file}.css");
routes.IgnoreRoute("{file}.png");
routes.IgnoreRoute("{file}.pdf");
routes.IgnoreRoute("{file}.htm");
routes.IgnoreRoute("{file}.html");
routes.IgnoreRoute("{file}.swf");
routes.IgnoreRoute("{file}.txt");
routes.IgnoreRoute("{file}.xml");
routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.ico(/.*)?" });
for (int i = 0; i <= 10; i++)
{
routes.MapRoute(
// Route name
"RouteName" + i.ToString(),
// URL with parameters
"{language}/{controller}/{action}/{para1}",
// Parameter defaults
new
{
action = "Index",
language = "de",
para1 = 0
},
//Parameter constraints
new { language = "de|en", controller = "SomeNameOfAnActualController" + i.ToString() }
);
}
routes.MapRoute(
"DefaulRoute", // Route name
"{controller}/{action}", // URL with parameters
new
{
controller = "Home",
action = "Index",
}
);
routes.MapRoute("404-PageNotFound", "{*url}", new { controller = "Error", action = "PageNotFound", language = "de" });
}
EDIT
The sample code was compiled against MVC2 now. In VS2010 MVC2 can be compiled against .NET 3.5 or 4.0.
The performance with 3.5 is good and 4.0 is bad.
I guess this means that the poorly performing part is not in a MVC assembly but in a framework assembly (like System.Web.Routing.dll). The question is still the same: Can I do something about it? An accepted answer would also be: No, the code is slow because from version 3.5 to 4.0 MS changed XXX
EDIT-2
I decompiled the part of System.Web.Routing.dll that takes to long. It uses a compiled regular expression. There is a code path (constraint2.Match ) that returns without executing the regex, but I did not check yet if it internally uses a different expensive operation.
protected virtual bool ProcessConstraint(HttpContextBase httpContext, object constraint, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
object obj2;
IRouteConstraint constraint2 = constraint as IRouteConstraint;
if (constraint2 != null)
{
return constraint2.Match(httpContext, this, parameterName, values, routeDirection);
}
string str = constraint as string;
if (str == null)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, SR.GetString("Route_ValidationMustBeStringOrCustomConstraint"), new object[] { parameterName, this.Url }));
}
values.TryGetValue(parameterName, out obj2);
string input = Convert.ToString(obj2, CultureInfo.InvariantCulture);
string pattern = "^(" + str + ")$";
return Regex.IsMatch(input, pattern, RegexOptions.CultureInvariant | RegexOptions.Compiled | RegexOptions.IgnoreCase);
}
There are solved problem similar to yours: First call to Url.Action on a page is slow
there are conclusion about routing constraints with regexp constraints that is very slow.
Each view is compiled and cached when it is used the first time. However, since the aspx Views were not designed specifically for Mvc each Url.Action is not compilede once for all in the final link but it is re-computed at each execution. Razor compiler has better optimization.
The only solution is computing the various linkks with Url.Action and storing them into some application level property, so it is computed just at first execution. You can put them either in the Application dictionary, or in static properties of a class.
I am not sure to the cause of what you are seeing, but it may not only be an MVC 1 vs MVC 4, IIS setup in later versions can impact the speed of view rendering. I came across a slide deck a few months ago that I thought was pretty interesting, relating to performance improvement tips in MVC 3 apps.
http://www.slideshare.net/ardalis/improving-aspnet-mvc-application-performance
Specifically, take a look at slide 28, which states:
Uninstall IIS UrlRewrite Module
If no applications on the server are using it
No effect in MVC apps before v3
Enhances speed of URL generation
I take this to mean that the UrlRewrite module will negatively impact MVC 3, but not MVC 2 or 1, which could be a source of the slowdown that you are seeing. There are some other improvements as well, but I don't believe that any of them 'directly' relate to what you are seeing.

Link in validation summary message

Is it possible to put a HTML link in validation summary message? For example I want to put a link to another page in case there is validation error:
#Html.ValidationSummary(False, "read more")
or
#Html.ValidationSummary(False, "read " &
Html.ActionLink("more", "helpforerror").ToHtmlString)
But in the browser the tag is escaped so it doesn't form a link.
I know you have accepted an answer, but i think my solution is more simple and will require less rewriting if you want to add links to existing validation summaries.
You need to put a {0} type format item in your validation message like below, which will be replaced by your link.
ModelState.AddModelError("", "Some error message with a link here {0}.");
then in your view call your validation summary like so:
#string.Format(Html.ValidationSummary().ToString(), Html.ActionLink("Click Here", "Action_To_Link_To")).ToHtmlString()
In this case i have used an extension method I added to the string object .ToHtmlString() that basically just converts the string to an HtmlString preventing any of the markup being escaped. it looks like this:
public static HtmlString ToHtmlString(this String str)
{
return new HtmlString(str);
}
Finally I chose another way to do it: create a div containing the link etc. outside of validation summary, and add the div only if modelstate is not valid:
#If Not ViewData.ModelState.IsValid Then
#<div>read more</div>
End If
This is inspired by an answer to similar question.
The validation text is encoded before the ValidationSumary or ValidationFor, etc...
you just need tu decode the html, then create an MvcHtmlString ...
Exemple :
#HttpUtility.HtmlDecode(Html.ValidationSummary().ToString()).ToMvcHtmlString()
this is an extension i have made to make MvcHtmlString :
namespace System
{
public static class StringExtension
{
public static System.Web.Mvc.MvcHtmlString ToMvcHtmlString(this string value)
{
return System.Web.Mvc.MvcHtmlString.Create(value);
}
}
}
or you can create an HtmlHelper if you plan to reuse this:
namespace System.Web.Mvc.Html
{
public static class FormHelper
{
public static MvcHtmlString ValidationSummaryEx(this HtmlHelper htmlHelper, bool excludePropertyErrors)
{
var original = htmlHelper.ValidationSummary(excludePropertyErrors);
var decoded = HttpUtility.HtmlDecode(original.ToString());
return decoded.ToMvcHtmlString();
}
}
}
Hope it help you or future viewer.
Note: it work for all validations Summary and ValidationFor ...
No, the default behaviour doesn't allow it, but you can make your own. This is what you need: Html raw in validationsummary
You can check if form is valid by jquery and update div with link text:
<div id="divToUpdate">
</div>
$('form').submit(function(){
if(!this.valid())
$('#divToUpdate').html("read <a href='anotherpage.html'>more</a>");
});
If you're sending back HTML in the ModelStateError, you can use this one liner:
#Html.Raw(HttpUtility.HtmlDecode(Html.ValidationSummary().ToHtmlString()))
It's very similar to what #Benoit had suggested, just without needing the extension.

MVC 3: Add usercontrol to Razor view

I have a DLL that contain a user control inside, in the Web Form view i can easily use it by using
<%# Register Assembly = "..." Namespace = "..." TagPrefix = "..." %>
But how to do it in Razor view?
You can't add server side controls to Razor views. In general it is very bad practice to do so anyways in an ASP.NET MVC application. Due to the heritage of WebForms view engine you could violate this rule but in Razor things have been made clearer.
This being said you could still do some pornography in Razor and include a WebForms partial which will contain the user control (totally not recommended, don't even know why I am mentioning it but anyway):
#Html.Partial("_Foo")
where in _Foo.ascx you could include server side controls:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%# Register Assembly="SomeAssembly" Namespace="SomeNs" TagName="foo" %>
<foo:SomeControl runat="server" ID="fooControl" />
Also, not recommended, but you can render a control in code, like in an HTML Helper:
public static string GenerateHtmlFromYourControl(this HtmlHelper helper, string id)
{
var yourControl = new YourControl();
yourControl.ID = id;
var htmlWriter = new HtmlTextWriter(new StringWriter());
yourControl.RenderControl(htmlWriter);
return htmlWriter.InnerWriter.ToString();
}
and then you can reference it from your view:
Html.GenerateHtmlFromYourControl("YourControlId")
Just make sure you set up/reference your namespaces correctly to do this.
Caveat
FYI, I'm pretty sure there are some severe limitations regarding the Page Lifecycle here...

Resources