I'm working on small web form,in C#/ASP.NET. I want to store the errors messages into variables of C# class; something like this:
public static class ErrorMessages {
public static string fooX = "baa";
// etc..
}
And then concat it in some attribute of an ASP tag:
<asp:RegularExpressionValidator runat="server"
ControlToValidate="baain"
ErrorMessage= *ErrorMessages.fooX*
/>
Is it possible? if yes, how to do this?
In the aspx page you may try:
ErrorMessage='<%# ErrorMessages.fooX %>'
In your code behind on page load call DataBind();:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataBind();
}
}
I am not sure about concatenating the aspx part of the page, you can set the ErrorMessage property of your RegularExpressionValidator in the code behind. Something like:
RegularExpressionValidator1.ErrorMessage = "Your message";
or
RegularExpressionValidator1.ErrorMessage = ErrorMessages.fooX;
One approach to this, is to create your own custom expression builder.
The ExpressionBuilder class is the base class for expression builders, such as the AppSettingsExpressionBuilder class, that create code expressions during page parsing.
Expression builders parse declarative expressions and create code to retrieve values bound to a control property. In no-compile scenarios, an expression builder that supports a no-compile feature evaluates the expression during run time.
Please see the link from msdn for more detailed explanation and example.
http://msdn.microsoft.com/en-us/library/system.web.compilation.expressionbuilder.aspx
This is simple, have you tried this:
<%= YourNamespace.YourConstant %>
Or (.Net 4, this option will automatically encode the text)
<%: YourNamespace.YourConstant %>
There are several operators:
<%# Used for data binding
<%$ Used for expressions, not code; often seen with DataSources:
<%= Returns a string
<%: Same as <%= but it auto-html-encodes the value within the tag
Edit 1
Well I just tested and it appears that you cannot use inline code with server controls...
So alternative approaches:
Simply assign the value using code behind
this.myRegularExpressionValidator.ErrorMessage = ErrorMessages.Foo;
Use resources instead. With resources you will gain many benefits like localization for your site and since resources are simply xml files, you can drop them in your site without recompile (assuming you are not using satellite assemblies to store your resources)
<asp:RegularExpressionValidator runat="server" ErrorMessage="<%$ Resources:Resource, MyResource %>" />
Where
Resource refers to the global resource file
MyResource refers to the key in the resource file containing the text
The global resources must be placed in the App_GlobalResources ASP.Net special folder, as an example the resource file name: Resource.resx
Example of the resource file
<?xml version="1.0" encoding="utf-8"?>
<root>
<data name="MyResource" xml:space="preserve">
<value>My error message</value>
</data>
</root>
The resource files can be added and managed using Visual Studio so you do not have to deal manually with the XML
Related
I have an aspx page using only inline C# without a codebehind.
Running from Visual Studio it works, however adding the aspx file to the wwwroot of my local machine gives the message
Compiler Error Message: CS1513: } expected
If I rearrange the code to have the method above the code the message is instead
CS1519: Invalid token 'try' in class, struct, or interface member declaration
I expect it is something to do with server configuration, though I don't really know where to start.
The issue only occurs if there is methods, removing method1 from the below results in correct running.
This is the minimum entire file I was able to cause the error with
html
<%# Page Language="C#" %>
<%
try
{
string message = "Text";
Response.Write(method1(message));
}
catch
{
Response.Write("Err");
}
string method1(string source)
{
return source;
}
%>
If you're embedding code directly on the aspx page, that code still has to go in a method. Ex:
<%# Page Language="C#" %>
<%
void Page_Load(Object sender, EventArgs e)
{
try
{
string message = "Text";
Response.Write(method1(message));
}
catch
{
Response.Write("Err");
}
}
string method1(string source)
{
return source;
}
%>
By the way - we don't typically put C# code directly in the .aspx file. That's what the code behind system is for.
And we don't typically write directly to the response. It's hard to control where the markup will end up. In Web Forms, it's better to declare a control on the page and then add markup to that (or show/hide controls). Of course if we're going to talk about doing things well - then don't use Web Forms in the first place. It's a dead technology.
I have messed around with the Visual Studio project, running on an earlier version of .NET/C# yields the following error, It seems possible that this is the actual problem I have had
Error CS8059 Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater.
I am unsure why it thinks method1 is a local function and details are hard to come by.
Edit: To solve my problem I put the method in script tags instead of embedded code blocks. The methods then could be used from the embedded blocks and the script tag.
<script runat="server">
string method1(string source)
{
return source;
}
<script>
I am attempting to use the Global.asax file and it is failing miserably. Every line in the code has an error but the funny thing is that it does not matter how many lines, what the lines contain, etc have as it always reports an error. This makes me thing there is a configuration setting that isn't right but wouldn't know where to begin.
The project is a Web Site rather than a Web Application but I read up on Global.asax and it appears to be acceptable to use it in a Web Site. I have provided the code I am using to test that the Global.asax works in the project before writing the code needed for the project.
<%# Application Language="C#" %>
<script runat="server">
static string _pagePath;
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
_pagePath = Server.MapPath("~/Folder/Page.aspx");
}
// ...
void Application_BeginRequest(object sender, EventArgs e)
{
string path = Request.PhysicalPath;
if (path == _pagePath)
{
Response.Write("Page viewed");
Response.End();
}
}
</script>
I have also provided a list of example error messages that are cropping up
'Class' statement must end with a matching
'End Class' 'If', 'ElseIf', 'Else', 'End If', 'Const', or 'Region' expected
'Namespace' statement must end with a matching 'End Namespace'
Statement cannot appear outside of a method body/multiline lambda.
Hopefully someone can pick out what I did wrong so I can use the Global.asax. Any help is widely appreciated!
add Language="C#" property to the directive at the top of your global.asax. right click on the file, choose view markup, add the property and rebuild.
<%# Application Codebehind="Global.asax.cs" Inherits="GLOBAL CLASS" Language="C#" %>
I've been given the task of updating an old OCX using C#. Everything works fine apart from one thing.
I've now been told that we need to add in a Param specifying a port.
The old HTML looked like this:
<object classid="clsid:D636293D-5687-4847-B53E-D4B4F3FABAD0" id="ActiveXTest3">
<param name="Port" value="8085" />
</object>
The main requirement is that the code to display the control is kept in a static html page.
No Javascript allowed (not sure why but it's what I've been told!)
Now doing some digging some posts say its not possible in .NET. Some say it is possible but hosting the object as an ASPX page. I've found some reference to using
IPropertyBag
in my C# ActiveX Control but can't find any definitive solution or answer.
Can someone clear this up and if possible a simple example?
use a com visible interface and place there something like
String Text { set;get;}
And, In the control class place something like
public String Text
{
get
{
return mStr_Text;// mStr_Text is private variable declared in the control class//
}
set
{
mStr_Text = value;
this.label1.Text = value.ToString();// will change the label's Text
}
}
After that you can place the param name as Text.
After switching to .net 4.0, some javascript code from a third party gridview crashes.
It has got something to do with HtmlEncode and UrlEncode now encode single quotation marks
So before some code on the page was inserted like this:
DataItem.GetMember('Id').Value
and now its like this: DataItem.GetMember('Id').Value
The gridview does an eval on that line, and crashes with a syntax error now. I can't change the javascript code in that gridview.
Is there anyway to solve this, without going backwards like this?
<pages controlRenderingCompatibilityVersion="3.5" />
EDIT: the pages controlRenderingCompatiblityVersion doesn't fix this also. Single quotes are still encoded.
From what I've read, it's a security feature and Microsoft is mum about changing it. The only work-around I've seen is you will need to create a custom encoder class. You can turn-off attribute encoding using this:
public class HtmlAttributeEncodingQuote : System.Web.Util.HttpEncoder
{
protected override void HtmlAttributeEncode(string value, System.IO.TextWriter output)
{
output.Write(value);
}
}
Then add this to web.config under system.web:
<httpRuntime encoderType="HtmlAttributeEncodingQuote"/>
My web app is a solution built on top of another solution. The base solution is meant to be a platform for multiple products. For the most part, this works fine, but weird things happen when I create product specific views.
I am using ViewUserControl<SomeViewModel> for my code behind class. In my code behind, I have access to this.Model and all the other goodies I'd expect from this class. But in my ascx file, I get red squiggley lines when I try to access this.Model or other properties defined in ViewUserControl. I also get red squiggley lines when I try to access properties defined directly in my code behind.
What's more interesting is, I don't get any real errors from this. The view renders just fine at run time and does not give me any build errors. But my ascx file thinks there will be errors. If I create the exact same view in the platform namespaces, it works fine. No red squiggles.
I find this to be really annoying. It's not a show stopper by any means, but if I'm going to be using an IDE with intellisense and all that jazz, I'd sure like it to work properly, and pick up the properties that are supposed to be there.
Has anyone else run into this? Do you know of a way to fix this?
Thanks!
Edit
It was requested that I post some code. Here's the code behind:
namespace MyProject.MyProduct.Web.Views
{
public class EditSearch : ViewUserControl<SearchResultsViewModel>
{
public bool IsSearchTypeA()
{
...............
}
public bool IsSearchTypeB()
{
...............
}
}
}
And here's my ascx:
<%
if (!this.IsSearchTypeB())
{
string categoryPageTitle = this.Model.SearchWidgetParameters.Search.CategoryPageTitle;
string categoryPageUrl = this.Model.SearchWidgetParameters.Search.Filters.CategoryPageUrl;
if (!string.IsNullOrEmpty(categoryPageUrl))
{
%> <div id="coid_website_backtoCategoryPageLink"> <%
string tocGuid = this.Model.SearchWidgetParameters.Search.Filters.TocGuid;
if (!string.IsNullOrEmpty(tocGuid))
{
categoryPageUrl += "?guid=" + tocGuid;
}
var backToLink = new HyperLink();
if (this.IsSearchTypeA())
{
backToLink.Text = "Edit Search";
}
else
{
backToLink.Text = "Back to " + TranslatedHtmlTextWriter.Translate(categoryPageTitle);
}
backToLink.NavigateUrl = TransactionOperations.AddContextToUrl(categoryPageUrl.StartsWith("/Browse/") ? categoryPageUrl : "/Browse/" + categoryPageUrl,
WebsiteTransitionType.Default, // Requested: CategoryPage
TransactionOperations.DefaultContextData);
backToLink.RenderControl(this.Writer);
%>
</div>
<%
}
}
%>
Edit
For those of you who are telling me that ASP.NET MVC cannot or does not use code behind, I'm sorry but this is horse hockey. This project has existed for years and there is a widely used product that runs on it. My product is only just recently jumping onto the Platform. The Platform solution uses code behind all over the place, and it works fine. In fact, it works fine at runtime in my product's solution as well, I just have the problem that my ascx file doesn't seem to know about my code behind. Furthermore, ViewUserControl is a System.Web.MVC class. Are you still going to tell me that code behind isn't used in ASP.NET MVC?
Since you are developing MVC you cannot use code behind. Instead, what do you think about adding this at the top of your .acsx file:
<%# Import Namespace="Namespace.Model" %>
Then you can access everything you have in there without so much complication.
ASP.NET MVC does not use code behind. It sounds like you are mixing ASP.NET MVC and ASP.NET WebForm pages.
I suggest you take a look at http://www.asp.net/mvc. It has some great tutorials on getting started with MVC and how it works.