How do I import a namespace in Razor View Page? - asp.net

How to import a namespace in Razor View Page?

Finally found the answer.
#using MyNamespace
For VB.Net:
#Imports Mynamespace
Take a look at #ravy amiry's answer if you want to include a namespace across the app.

The first way is that use #using statement in .cshtml files, that imports a namespace to current file only, and the second:
In the "web.config" file in "Views" directory of your project (notice it is not the main web.config in project's root), find this section:
<system.web.webPages.razor>
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
.
.
<!-- etc -->
</namespaces>
</pages>
</system.web.webPages.razor>
you can add your custom namespace like this:
<add namespace="My.Custom" />
that will add the namespace to all of .cshtml (and/or .vbhtml) files;
also you can change views inheritance from here, like:
<pages pageBaseType="My.Custom.MyWebViewPage">
Regards.
UPDATE: Thanks to #Nick Silberstein to his reminder about areas! He said:
If you're working within an area, you must add the namespace within the Web.config under /Areas/<AreaName>/Views/ rather than
/Views/

For Library
#using MyNamespace
For Model
#model MyModel

In ASP.NET MVC 3 Preview1 you can import a namespace on all your razor views with this code in Global.asax.cs
Microsoft.WebPages.Compilation.CodeGeneratorSettings.AddGlobalImport("Namespace.Namespace");
I hope in RTM this gets done through Web.config section.

I found this http://weblogs.asp.net/mikaelsoderstrom/archive/2010/07/30/add-namespaces-with-razor.aspx which explains how to add a custom namespace to all your razor pages.
Basically you can make this
using Microsoft.WebPages.Compilation;
public class PreApplicationStart
{
public static void InitializeApplication()
{
CodeGeneratorSettings.AddGlobalImport("Custom.Namespace");
}
}
and put the following code in your AssemblyInfo.cs
[assembly: PreApplicationStartMethod(typeof(PreApplicationStart), "InitializeApplication")]
the method InitializeApplication will be executed before Application_Start in global.asax

One issue that you must know is that when you import a namespace via web.config in Views folder, that namespace is imported JUST for views in that folder. Means if you want to import a namespace in an area views, you must also import that namespace, in that area's web.config file, located in area's Views folder;

For namespace and Library
#using NameSpace_Name
For Model
#model Application_Name.Models.Model_Name
For Iterate the list on Razor Page (You Have to use foreach loop for access the list items)
#model List<Application_Name.Models.Model_Name>
#foreach (var item in Model)
{
<tr>
<td>#item.srno</td>
<td>#item.name</td>
</tr>
}

You can try this
#using MyNamespace

"using MyNamespace" works in MVC3 RTM. Hope this helps.

I think in order import namespace in razor view, you just need to add below way:
#using XX.YY.ZZ

Depending on your need you can use one of following method:
In first line/s of view add "using your.domainName;" (if it is
required in specific view only)
if required in all subsequent views
then add "using your.domainName;" in _ViewStart.cshtml. You can find
more about this in: Where and how is the _ViewStart.cshtml layout file linked?
Or add Assembly reference in View web.config as described by others explained in: How do you implement a #using across all Views in Asp.Net MVC 3?

Related

Type 'ASP._Page_index_cshtml' does not inherit from 'System.Web.WebPages.WebPage'

I am getting:
Type 'ASP._Page_index_cshtml' does not inherit from 'System.Web.WebPages.WebPage'.
when I browse to my index.cshtml file. It is very simple:
#using System.Web.Optimization
#inherits System.Web.Mvc.WebViewPage
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width">
<title>Hello World</title>
#Styles.Render("~/Content/css", "~/Content/themes/base/css")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
#Scripts.Render(
"~/bundles/jquery",
"~/bundles/jqueryui"
)
</body>
</html>
my index.cshtml file is outside of the Views folder, if that matters at all.
Do not remove the inheritance, it might be necesary and might lead to another problems in the future.
Instead try this:
Enable "View all Files" in the web project that is failing, and search for a file that seems correct but is not included in visual studio, and delete it. If it fails in your deployment folder, try to clean the folder as well, and re-deploy the site, you might have unnecesary files that might cause the same problem.
In my case, at the root of the webproject I had an extra copy of _ViewStart.cshtml (excluded from the project), I deleted that file, and that did the trick.
Hope it helps, let me know if this solve your problem as well.
I just had to remove: #inherits System.Web.Mvc.WebViewPage
Looks like I had a copy paste error when reorganizing my project.
I change the cshtml line from:
Layout = "~/Views/_ViewStart.cshtml";
to
Layout = "~/Views/Shared/_Layout.cshtml";
since _ViewStart.cshtml contains only that line of code. Layout file was required because it contains the script to client-side validation.
It worked also when I remove the line, but I prefer to keep _Layout.cshtml included.
What worked for me was to add...
#inherits System.Web.Mvc.ViewStartPage
...to the top of _ViewStart.cshtml.
I think the reason this worked for me was because of my ~/Views/Web.config file. In it I had placed the following block in order to avoid a bunch of #inherits calls on my views...
<configuration>
<system.web.webPages.razor>
<pages pageBaseType="System.Web.Mvc.WebViewPage"> <!-- Notice pageBaseType -->
...
</pages>
</system.web.webPages.razor>
</configuration>
I think this instructed the razor engine that all views including _ViewStart.cshtml were to be of type System.Web.Mvc.WebViewPage. This is not the same type as System.Web.Mvc.ViewSTartPage and hence the error. Putting #inherits System.Web.Mvc.ViewStartPage at the start of _ViewStart.cshtml explicitly specifies the required type for _ViewStart.cshtml.
It could be that an older version of System.Web.WebPages.dll is loaded to memory, and it tries to cast the your cshtml page to a version of WebPages class from that dll.
To test this, try to see what http modules are currently registered:
var allModules = HttpContext.Current.ApplicationInstance.Modules;
for( int i = 0; i < allModules.Count; i++ ) {
Trace(allModules.GetKey(i));
}
In my case that was:
....
__DynamicModule_System.Web.WebPages.WebPageHttpModule, System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35_bca8e05a-5746-45b0-be95-2b920b455ccf
__DynamicModule_System.Web.WebPages.WebPageHttpModule, System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35_c1a67b42-31a9-47f1-8483-9e712fabe2a7
To fix the problem you need to replace the older version of System.Web.WebPages.dll in your /Bin folders, or some other dll-s that might be referencing it.
Just delete the _ViewStart.cshtml and re-add.
No need to take Tension. Just follow 2 basic steps
Delete the _ViewStart.cshtml
Make statement to a comment. Means for the following statement in index view:
Layout = "~/Views/_ViewStart.cshtml";
and mark it as a comment:
//Layout = "~/Views/_ViewStart.cshtml";
Comment Layout variable in your .cshtml file
//Layout = "~/Views/_ViewStart.cshtml";
Why are you trying to browse directly to a view? And why isn't it in a views folder?
To get a basic "Hello World" page up you first want to create a controller called HomeController.cs:
using System.Web.Mvc;
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
Then create a file /Views/Home/Index.cshtml and put your markup in that. You may also need to add:
#{
Layout = null;
}
to the top of the page since it doesn't look like you are using a master page.
As a side note, all this assumes you haven't screwed with your default routing.
Remove the web.config from your Views folder.
As you're including Partial1.cshtml from that folder, it is also including the web.config from within there. And that web.config is saying that all pages must inherit from WebViewPage.

In MVC3, is it possible to create reuseable functions in view?

I'm not talking about javascript functions, but server side functions written in c#.
For the html table in my view, I'm creating table headers that act like sortable columns. But the sortability depends on a complex logic so I want to put the logic into a function instead of writring it for each column.
#Amr ElGarhy
Thank you for suggesting customer helper, but the helper class I create is not being regonizied.
Helper Code:
namespace MyHtmlHelpers
{
public static class CustomHelpers
{
public static string MySortColumn(this HtmlHelper helper, string label, string col, string dir, UrlHelper url)
{
return string.Empty;
}
}
}
web.config:
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages"/>
<add namespace="MyHtmlHelpers"/>
</namespaces>
</pages>
But in View, neither #HtmlHelper.MySortColumn nor #Html.MySortColumn is regonized. Am I missing something here? I even restarted my pc.
UPDATE
adding namespace in web.config didn't work for me. adding in View page works.
I think you need to take a look at HTML Helpers and how to create a custom one:
http://www.asp.net/mvc/tutorials/creating-custom-html-helpers-cs
http://www.asp.net/mvc/videos/how-do-i-create-a-custom-html-helper-for-an-mvc-application
Try this
helper syntax
It's better to create base class with the logic and derive your views from this class. Normally you shouldn't reveal/share any methods to reuse between views.
Are you using areas? Areas have their own view folder and usually have their own web.config. If that's the case, you can try to add namespace to that web.config.
Also, web.config files are resolved hierarchically through folders. It means you can have web.config in your base Area directory which affects all area specific views.
In my case, I have two web.config files where I add my namespaces - one is in View directory and other one in Area directory.

asp.net calling code inline not working

In my code behind, I can do the following in the onload:
string x = Fmg.Cti.UI.Utilities.Classes.ResourceController.ReadResourceValue("Riblet", "Riblet_Chicklet1_Button_text");
This works without issue.
In my aspx page (I didn't remove the code from the onload), I put this:
<%= Fmg.Cti.UI.Utilities.Classes.ResourceController.ReadResourceValue("Riblet", "Riblet_Chicklet1_Button_text")%>
When I do, I got an error:
error CS0234: The type or namespace name 'Cti' does not exist in the
namespace 'Fmg' (are you missing an assembly reference?)
I had this (or something quite similar) working. I don't know how I broke it.
Thanks again for your help.
You need to register the assemblies you're using in your page as well (just like usings in your code behind). See Do I have to add "<%# Register assembly=" to every page?
Do you have that namespace imported? For asp.net you can do something like the following to make namespaces available for inline coding.
<%# Import Namespace="Fmg.Cti.UI.Utilities.Classes" %>
You can make namespaces generally available to all of your asp.net pages for inline coding by adding the namespaces into the web.config
<system.web>
<pages>
<namespaces>
...
<add namespace="Fmg.Cti.UI.Utilities.Classes" />
...
</namespaces>
</pages>
</system.web>

Problem with using the MvcReCaptcha library in a view

The MvcReCaptcha library looks very solid, and appears to have some good developer adoption, but when I tried it for the first time today, using the supplied HTML helper, my app won't run. I have the helper in a partial view as follows:
<fieldset>
<legend>3. Verify that you are a human.</legend>
#Html.GenerateCaptcha()
</fieldset>
I have the namespace included in web.config as instructed:
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="MvcReCaptcha.Helpers"/>
</namespaces>
</pages>
(Other namespaces removed for brevity)
And I have my private and public keys defined in appSettings. I can see no way that I deviate from the examples on the CodePlex page except that I am using Razor. Can anyone offer some insight into what I may be doing wrong?
If you are using Razor you need to add the MvcReCaptcha.Helpers namespace to the <namespaces> section of ~/Views/web.config file and not the one in ~/web.config.

How to use extensions and utility methods in markup?

Ok. This is probably a really stupid question, but I'm going to ask it anyway...
How can I use extensions and utility methods in my ASP.Net markup? For example, (say) I have a DateTime extension method called "ToExampleString()" (contained in the DateTimeExtensions class in my Common.Extensions project) and I want to use it in my markup in the ListView's ItemTemplate:
<ItemTemplate>
<span><%# ((DateTime)Eval("DateStarted")).ToExampleString() %></span>
</ItemTemplate>
I'm getting the following error:
'System.DateTime' does not contain a definition for 'ToExampleString' and no extension method 'ToExampleString' accepting a first argument of type 'System.DateTime' could be found (are you missing a using directive or an assembly reference?)
The page simply can't see the extensions method.
Similarly, how do I make my page's markup aware of a utility class:
<span><%# ExampleUtility.ProcessDate(Eval("DateStarted") %></span>
What steps do I need to take to make this stuff work? I assume I'm overlooking something stupidly obvious?
Thanks
You need to import the namespace either at the top of the page as others have said
<%# Import Namespace="Common.Extensions"%>
Or globally in your web.config
<system.web>
<pages>
<namespaces>
<add namespace="Common.Extensions"/>
</namespaces>
</pages>
</system.web>
If you simply need access to methods of a public module (or static class), just import your application's root namespace.
<%# Import Namespace="Common.Extensions" %>
I believe you can do that for all your markups in the web.config.
You have to import the namespace, at the top of the page:
<%# Import Namespace="Common.Extensions"%>
Namespaces?
You should add using/import directive in aspx markup

Resources