I just started using Razor instead of the WebForms-ViewEngine. Now in my Razor-View i have something like this:
#{
int i = 42;
string text;
if (i == 42)
{
text = "i is 42!";
}
else //i is not 42 //<- Error here
{
text = "i is something else";
}
}
I get a warning and at runtime it get an exception in the else line:
Expected a "{" but found a "/". Block statements must be enclosed in "{" and "}". You cannot use single-statement control-flow statements in CSHTML pages.
Apparently the compiler doesn't like comments between the else and the {. I also tried commenting with #* and /*, which gave similar error-messages.
Is there anyway to make a comment in razor like I want it?
Disclaimer:
Yes i know i could fix it simply like this:
#{
int i = 42;
string text;
if (i == 42)
{
text = "i is 42!";
}
else
{ //i is not 42
text = "i is something else";
}
}
However it doesn't fit our coding guidelines and having the comment on the same line makes my intentions more clear.
That's how the Razor parser is built. You could always submit a bug/feature request on MS connect if you don't like the way it is and hope that people will vote for it and it will be fixed/implemented in a future version of the parser. Personally I wouldn't because I don't care (see below why).
This being said, why care? I mean you are not supposed to write code in a Razor page. A Razor page is intended to be used as a view. In ASP.NET MVC a view is used to display some information from the view model that is passed to it from the controller action. Markup primary, mixed with HTML helpers and displaying information from the view model. But C# code is a no no. So what you call code and what you have shown in your question has strictly nothing to do in a Razor view.
Related
I am editing a document in draft mode Wordpress 5.2.2 in the Gutenberg editor, and add this Custom HTML block:
<pre><code class="language-typescript">const simple = <T>(cl: T) => cl;
class Hero {
constructor(public position: [number, number]) {}
}
interface { hello: number }
const errorOne = <T>(cl: T) => new cl(); // Cannot use 'new' with an expression whose type lacks a call or construct signature.</code></pre>
and it happily works as expected in preview. I save as draft.
When I return the HTML is ghosted and I get the error in the title. I can convert to HTML and it works again, but then it errors again when I return to it later.
It seems this error is talked about everywhere but the explanations are nonsense and resolve nothing.
If my Custom HTML is valid (which it seems to be), why does it work and then give an error. How do I fix this?
I think the main issue is not converting < & > properly in your code. They are missing the semicolon at the end of the string.
This code is working fine:
<pre><code class="language-typescript">const simple = <T>(cl: T) => cl;
class Hero {
constructor(public position: [number, number]) {}
}
interface { hello: number }
const errorOne = <T>(cl: T) => new cl(); // Cannot use 'new' with an expression whose type lacks a call or construct signature.</code></pre>
When you insert the code with missing semicolon, WordPress saved as is. However, when trying the load the page again WordPress compares the saved content (with missing characters) to the one generated from the block (which is probably attempting to display correct HTML). This process led to an error as both texts were not identical.
If you want to check the error yourself you can check the console through developer tool in your browser (F12 in Chrome).
The code below is what I am using for my invoices to be Posted
ledgerJournalTable = header.ledgerJournalTable();
if (ledgerJournalTable.RecId > 0)
{
ledgerJournalCheckPost = ledgerJournalCheckPost::newLedgerJournalTable(ledgerJournalTable, NoYes::Yes, NoYes::Yes);
// Post only if there is succesful validation.
if (ledgerJournalCheckPost.validate())
{
ledgerJournalCheckPost.run();
}
else
{
info("Error.");
}
}
but there is always an error that says:
"Journal does not exist"
All the values that I've placed on the fields are correct because when I tried to use the same values manually, it was posted.
What could be wrong when that error pops up?
Edit1: As I've used breakpoint, I found out that in LedgerJournalCheckPost.validate() the ledgerJournalTable.JournalNum is empty "".
Found out that the ledgerJournalCheckPost.run() already has/calls the validate() method inside it, so there's no need to call the validate() method. However, I still don't know how to solve if you're going to use the validate() method through x++o code.
I am trying to use the jQuery UI autocomplete feature in my web application. What I have set up is a page called SearchPreload.aspx. This page checks for a value (term) to come in along with another parameter. The page validates the values that are incoming, and then it pulls some data from the database and prints out a javascript array (ex: ["item1","item2"]) on the page. Code:
protected void Page_Load(object sender, EventArgs e)
{
string curVal;
string type ="";
if (Request.QueryString["term"] != null)
{
curVal = Request.QueryString["term"].ToString();
curVal = curVal.ToLower();
if (Request.QueryString["Type"] != null)
type = Request.QueryString["Type"].ToString();
SwitchType(type,curVal);
}
}
public string PreLoadStrings(List<string> PreLoadValues, string curVal)
{
StringBuilder sb = new StringBuilder();
if (PreLoadValues.Any())
{
sb.Append("[\"");
foreach (string str in PreLoadValues)
{
if (!string.IsNullOrEmpty(str))
{
if (str.ToLower().Contains(curVal))
sb.Append(str).Append("\",\"");
}
}
sb.Append("\"];");
Response.Write(sb.ToString());
return sb.ToString();
}
}
The db part is working fine and printing out the correct data on the screen of the page if I navigate to it via browser.
The jQuery ui autocomplete is written as follows:
$(".searchBox").autocomplete({
source: "SearchPreload.aspx?Type=rbChoice",
minLength: 1
});
Now if my understanding is correct, every time I type in the search box, it should act as a keypress and fire my source to limit the data correct? When I through a debug statement in SearchPreload.aspx code behind, it appears that the page is not being hit at all.
If I wrap the autocomplete function in a .keypress function, then I get into the search preload page but still I do not get any results. I just want to show the results under the search box just like the default functionality example on the jQuery website. What am I doing wrong?
autocomplete will NOT display suggestions if the JSON returned by the server is invalid. So copy the following URL (or the returned JSON data) and paste it on JSONLint. See if your JSON is valid.
http://yourwebsite.com/path/to/Searchpreload.aspx?Type=rbChoice&term=Something
PS: I do not see that you're calling the PreLoadStrings function. I hope this is normal.
A couple of things to check.
Make sure that the path to the page is correct. If you are at http://mysite.com/subfolder/PageWithAutoComplete.aspx, and your searchpreload.aspx page is in another directory such as http://mysite.com/anotherFolder/searchpreload.aspx the url that you are using as the source would be incorrect, it would need to be
source: "/anotherFolder/Searchpreload.aspx?Type=rbChoice"
One other thing that you could try is to make the method that you are calling a page method on the searchpreload.aspx page. Typically when working with javascript, I try to use page methods to handle ajax reqeusts and send back it's data. More on page methods can be found here: http://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx
HTH.
I have and ASP.NET 3.5 page where I need to debug some JavaScript code.
function checkAll(isChecked)
{
debugger;
var dataGridElements = document.getElementById('" + DataGridSearchResults.ClientID + #"').getElementsByTagName('input');
for (var i = 0; i < dataGridElements.length; i++)
{
var e = dataGridElements[i];
if ((e.type=='checkbox') && (!e.disabled))
{
e.checked = isChecked;
}
}
}
As you can see, I added a debugger statement in the first line. For some reason, when i execute the page, the javascript (which is in a string variable and registered with Page.ClientScript.RegisterClientScript statement) is in my source code twice! The second block doesn't have my debugger statement either! I checked the project, this block of Javascript is only listed once in the project.
Any ideas? (the client i am running on is IE8 if that makes a difference)
Figured it out. The base page that this control was on (the javascript was in an ASCX file) was a page that had a tab strip on it. One of the other tabs had the code copy and pasted with the exact same signature, just a grid name difference. Once i changed the signature on my set of code, it worked fine.
I want to set up an ASP.NET custom control such that it has a custom name, specifically, with a hyphen within it, so it might look like this in markup:
<rp:do-something runat="server" id="doSomething1" />
I don't mind if this syntax requires setting up a tag mapping in web.config or something to that effect, but the tagMapping element doesn't quite match up for what I'd like to do.
I wouldn't think this is possible due to the restrictions on class namings. I don't believe you can refer to a control class in markup without refering to it by name
Is there a specific reason you need the hyphen?
John, you're right. I did some searching in Reflector and it looks like it doesn't get there:
Type ITagNameToTypeMapper.GetControlType(string tagName, IDictionary attribs)
{
string str;
string str2 = this._nsRegisterEntry.Namespace;
if (string.IsNullOrEmpty(str2))
{
str = tagName;
}
else
{
str = str2 + "." + tagName;
}
if (this._assembly != null)
{
Type type = null;
try
{
type = this._assembly.GetType(str, true, true);
}
Implemented in System.Web.UI.NamespaceTagNameToTypeMapper, System.Web.
#Jonathan: I have a specific business reason for wanting to do it this way. Oh well.