I have a large html file that I want to split apart. I have managed to split it apart and place each part in a htm file. As a result my structure now looks like:
note all the files in the folder are just specific to the Default.aspx page. I like to have my code spitted into several parts; I find it easier to program that way.
Anyways why when I do:
<%
Response.WriteFile("_Menu.htm");
%>
that creates a different output that if I where to go to _Menu.htm copying the entire content and pasting it in there? I know I can create a user control for each file. but if I do so I will have to create a page directive at the root of the page for each file and plus I just need to place static content I don't need to call an aspx page. Why does Response.WriteFile include stuff that I don't have in the file. For example it places '"' marks whenever I have a paragraph.
EDIT
I use user controls when I plan to reuse html. In this case I am just spliting apart a page into several ones. I will like to have the content of each chunk in a separate file.
EDIT 2
Doing:
<%
//Response.WriteFile("_Menu.htm");
Response.Write(System.IO.File.ReadAllText(#"A:\Users\Antonio\Dropbox\VisualStudio Projects\Websites\Boat\Boat\MasterPages\User\_Menu.htm"));
%>
works great. why is Response.WriteFile including " (paragraph) " at the the beginning!?
create your Response.Write method:
Create the following extension method globaly so all your pages can access it:
using System.Web.UI;
public static class StaticExtensionMethods
{
public static void Include(this System.Web.UI.Page Page, string path)
{
Page.Response.Write(System.IO.File.ReadAllText(Page.Server.MapPath(path)));
}
}
then do:
<%
this.Include("_Menu.htm");
%>
Related
I want to use pure html page instead of cshtml with MVC .net.
But when I add view by right clicking Index i can see only two options.
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}}
Cshtml (Razor)
Aspx
I followed
Can I serve .html files using Razor as if they were .cshtml files without changing the extension of all my pages?
forum but still no help. I still don’t see an option to add html instead of cshtml
I also tried adding html page directly to view folder but i dont know how to point that view from my controller function.
Replacing Index.cshtml with Index.html gave me this error
The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Home/Index.aspx
~/Views/Home/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Home/Index.cshtml
~/Views/Home/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml
In order to render plain HTML file you can use
return new FilePathResult(HtmlPath, "text/html");
where HtmlPath is
Server.MapPath(string.Format("~/Views/{0}/{1}.html", YourControllerName, YourHtmlfileName))
You can create a View with a regular cshtml file add it to the controller and in the View itself just use pure html and add the following to the top:
#{
Layout = null;
}
This way you use a cshtml file that doesn't use you master layout file. And just serves whatever html you put in it.
If it's a static html file you don't need to point your controller to it, because IIS can serve them just fine. Add an html file to your project (anywhere but NOT in the viewsfolder), and point your browser to that file.
If you right click on your Content folder you can select 'Add new item...'. You can then select 'Web' in the tree on the left and choose the 'HTML Page' on the right.
This should add you an HTML page.
Add a file. Rename it.
F2 in solution explorer.
Right now, I'm having trouble.
First of all I have a page, let's call it "http://blah.com/login".
That obviously goes strait to "index.asp"
A line of Main.asp:
<!--#include file="resource/menu.asp"-->
Page top includes all of what I need for my menu... so:
Part of resource/menu.htm:
<div id="colortab" class="ddcolortabs">
<ul>
<li><span>Main</span></li>
...
</ul>
</div>
<!--Main drop down menu -->
<div id="dropmain" class="dropmenudiv_a">
Announcements
Contact Information
Meeting Plan
Photo Gallery
Upcoming Events
</div>
Let's say I click on the "announcements" (http://blah.com/login/main/announcements.asp) link... Now I'm at the announcements page!
But wait, I include the same menu file. Guess what happens:
I get sent to "http://blah.com/login/main/main/announcements.asp
Which doesn't exist...
My solution:
Make a menu_sub.asp include for any subpages.
But wait a second... this WORKS, but it gets REALLY REALLY messy... What can I do to use just one main "menu.asp" instead of "menu_sub.asp"? using "/main/announcements.asp" WON'T be an option because this is a web application that will be on different directories per server.
There is no magic bullet fix. Here is how I would do this.
Create a separate include file that DIM's and Initializes global variables called info.asp
Inside info.asp DIM a variable called strRelativePath and initialize it to ""
Include info.asp at the top of each asp page above the menu.asp include
Modify menu.asp and include <%=strRelativePath%> in all the urls
Inside each asp page set strRelativePath as necessary:
<!--#include file="includes/info.asp"-->
strRelativePath = "Login/"
<!--#include file="resource/menu.asp"-->
Add this function to your menu.asp:
Function GetApplicationPath()
GetApplicationPath = Mid(Request.ServerVariables("APPL_MD_PATH"), Len(Request.ServerVariables("INSTANCE_META_PATH")) + 6) & "/"
End Function
Dim prefix: prefix = GetApplicationPath()
Now structure your references in the menu.asp using:
Announcements
This will make these references absolute but they will vary appropriately with whatever virtual folder path the website has your ASP application installed under.
There is a similar question here where the highest rated answer states that you can find the root with the following function:
Function ToRootedVirtual(relativePath)
Dim applicationMetaPath : applicationMetaPath = Request.ServerVariables("APPL_MD_PATH")
Dim instanceMetaPath : instanceMetaPath = Request.ServerVariables("INSTANCE_META_PATH")
Dim rootPath : rootPath = Mid(applicationMetaPath, Len(instanceMetaPath) + Len("/ROOT/"))
ToRootedVirtual = rootPath + relativePath
End Function
You can then call it:
ToRootedVirtual("/")
or
ToRootedVirtual("/index.asp")
etc. to return the root from the server.
You can use Virtual instead of File because Virtual accepts an absolute path from the root directory, not relative like File.
Like this:
<!--#INCLUDE VIRTUAL="/resource/menu.asp"-->
Also, make sure your IIS settings allow Includes, See this link for details:
http://tech.mikeal.com/blog1.php/server-side-includes-for-html-in-iis7
This can be fixed with the HTML base tag:
Add this tag in the beginning of each page:
<base href="http://blah.com/login">
We have a multilingual site, or culture-sensitive, and some of the static content now needs to be targeted; for this I'm using themes as it seems the easiest way to achieve what I want, but I can't for the life of me get the images to pick up.
I'm setting the theme in code-behind, and thought at first that maybe this was the issue, but on checking up it looks like I'm doing the right thing (setting on Pre-Init).
I expect to be able to reference images using relative paths where App_Themes/ThemeName/ is automatically resolved, such as:
<asp:Image runat="server" ImageUrl="images\image.jpg"/>
For whatever reason, however, the image isn't being pulled through at all.
This is the code we have in place for setting the theme (the only really relevant part, I'm sure, being the Theme = CurrentSite.CultureName, which is applied successfully):
Private Sub SetTheme()
Dim themesPath = Server.MapPath("~/App_Themes")
If Directory.Exists(themesPath) Then
Dim themePaths = Directory.GetDirectories(themesPath)
Dim themePathInfo As DirectoryInfo
For Each _path In themePaths
themePathInfo = New DirectoryInfo(_path)
If Not themePathInfo Is Nothing Then
If themePathInfo.Name = CurrentSite.CultureName Then
Theme = CurrentSite.CultureName
Exit For
End If
End If
Next
End If
End Sub
In the above code, CurrentSite.CultureName would be a language culture name (for example, en-gb, or nn-no) that does have an existing corresponding theme folder containing all required resources.
Pages do have EnableTheming set to True. Also, I have tried removing the theme-setting code and applying the theme in the page using Theme="en-gb" to no avail.
Is there anything immediately evident as to why the URLs aren't resolved?
Use a Skin file to do this. Change your Image tag to:
<asp:Image runat="server" SkinID="SomeImage/>
And in your App_Themes\MyTheme\ folder, add a new Skin file (MyTheme.skin) and add this:
<asp:Image runat="server" SkinID="SomeImage" ImageUrl="images\image.jpg"/>
This image skin now points to image.jpg within the App_Themes\MyTheme\ folder.
For dynamic images you can do this in your BasePage (assuming you have one):
public string ThemePath { get { return "~/App_Themes/" + this.Theme + "/"; } }
public string MapThemePath(string relativePath)
{
return string.Format("{0}{1}", this.ThemePath, relativePath);
}
But, since I can't see what you're actually doing, I can't say this is the recommended solution. In general your theme contains only things needed or layout and display. You're talking about dynamic images which, to me, doesn't sound like it belongs in a theme? Not sure, just a thought.
I have a partial view (.ascx) that should include its own CSS file as it's used in multiple other views. How do I inject a stylesheet in the page server-side, i.e. without using JavaScript?
Dario - due to using this for partialviews, you're going to always have the problem that the <head> section of the document is already in place and therefore can't be modified. If you want to remain WC3 compliant, then you'll have to put any further css into the head section via javascript. This may or may not be desirable (if you've got to cater for downsteam browsers with javascript turned off).
the main problem that you may be aluding to is the fact that you can't put <asp:contentplaceholders> into your partials. this is a pain (tho understandable as the masterpage ref would tie the partial too closely to a particular master page).
To this end, I've created a little helper method that does the basic grunt work to put the css file into the head section automatically.
edit - (as per Omu's js suggestion) this is a nice little halfway house:
// standard method - renders as defined in as(cp)x file
public static string Css(this HtmlHelper html, string path)
{
return html.Css(path, false);
}
// override - to allow javascript to put css in head
public static string Css(this HtmlHelper html, string path, bool renderAsAjax)
{
var filePath = VirtualPathUtility.ToAbsolute(path);
HttpContextBase context = html.ViewContext.HttpContext;
// don't add the file if it's already there
if (context.Items.Contains(filePath))
return "";
// otherwise, add it to the context and put on page
// this of course only works for items going in via the current
// request and by this method
context.Items.Add(filePath, filePath);
// js and css function strings
const string jsHead = "<script type='text/javascript'>";
const string jsFoot = "</script>";
const string jsFunctionStt = "$(function(){";
const string jsFunctionEnd = "});";
string linkText = string.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}\"></link>", filePath);
string jsBody = string.Format("$('head').prepend('{0}');", linkText);
var sb = new StringBuilder();
if (renderAsAjax)
{
// join it all up now
sb.Append(jsHead);
sb.AppendFormat("\r\n\t");
sb.Append(jsFunctionStt);
sb.AppendFormat("\r\n\t\t");
sb.Append(jsBody);
sb.AppendFormat("\r\n\t");
sb.Append(jsFunctionEnd);
sb.AppendFormat("\r\n");
sb.Append(jsFoot);
}
else
{
sb.Append(linkText);
}
return sb.ToString();
}
usage:
<%=Html.Css("~/Content/yourstyle.Css")%>
or:
<%=Html.Css("~/Content/yourstyle.Css", true)%> // or false if you want!!
worth a back-pocket approach if all else fails. it may also be possible to adapt the logic above to hit an actionfilter and add the css to the reponse headers etc.., rather than outputting the js string.
Is there a reason you cannot just put the stylesheet in the main view page? Unless it is extremely large, it should not cause your page to load significantly slower when not being used, especially after compression.
Furthermore, if the partial view is being retrieved by ajax, you will end up re-downloading the css file multiple times (depending on the browser's caching).
I'm not an ASP.NET or MVC expert, but I am currently working on a project with it. Would it be possible to include something like this in the head of your master page?
<asp:ContentPlaceHolder ID="HeadContent" runat="server"></asp:ContentPlaceHolder>
Then somehow get your CSS into the content placeholder?
<asp:Content ID="styleSheetHolder" ContentPlaceHolderID="HeadContent" runat="server">
<link rel='stylesheet' href='yourstyle.css' type='text/css' />
</asp:Content>
It looks like you'd have to do this from the calling page, which would introduce duplication of code. I'm not sure how to get around that. Maybe it could it be done with an HTML helper.
A place I worked had a site with a lot of conditional partial views, which could and would change from time to time as new things were added to the application. The best way we found was to use naming conventions - naming the partial view, stylesheet and script the same (except extension, of course).
We added one or more stylesheets, scripts and partial views to the page's view model. We then used a custom HTML helper to loop through the relevant array in each content section and insert the required content. The pain was having to manage three or more files for each component, but at least we were able to reduce the amount of maintenance in the hosting pages.
Never did resolve the problem of putting a partial view inside a partial view, though.
Why not put the link tag in your partial view:
<link rel="stylesheet" href="yourstyle.css" type="text/css" />
I have a page name with XYZ.aspx
Now I want to change ABC.aspx how should I do it?
When i directly change it from solution explorer it gives me an error.
Can anyone help me on this?
Thank You
Smartdev
ASP.NET files are usually composed of 1-3 files total depending on the type of project and the file itself. That being said, there is always the markup *.aspx file, then optionally there will be a code-behind *.aspx.cs file and an additional and also optional designer file *.aspx.designer.cs. If you are renaming the file you will need to update code in various places based on the structure of the file itself.
In the event of more than 1 file making up your ASP.NET page you will want to update the .aspx file's header like so:
<%#Page CodeBehind="XYZ.aspx.cs" Inherits="XYZ" %>
to
<%#Page CodeBehind="ABC.aspx.cs" Inherits="ABC" %>
Then in the code behind file
public partial class XYZ : Page { }
to
public partial class ABC : Page { }
Finally, if there is also a *.designer.cs file you will want to update it as well:
public partial class XYZ : Page { }
to
public partial class ABC : Page { }
That should cover all of the files!
To change the name of an aspx file (I'm using vs2012) and associated files single click on filename in solution explorer and single click again to select the name of the file, change the name and enter... vs will rename the code behind file and designer file automatically and change the tags linking them. As nathan above said it does not rename the c# in the code behind to reflect the filename (which would be good practice)... nor importantly does it do a solution wide search for links and more oblique code references to the file. So it's best to do a manual find in files over the entire solution to check and all naming conventions are good.
That should do it