Microsoft MVC "echo/print/output" etc - asp.net

With ASP.NET's view engine/template aspx/ashx pages the way to spit to screen seems to be:
<%= Person.Name %>
Which was fine with webforms as alot of model data was bound to controls programatically. But with MVC we are now using this syntax more oftern.
The issue I have with it is quite trivial, but annoying either way. This is that it seems to break up the mark up i.e.:
<% foreach(var Person in People) { %>
<%= Person.Name %>
<% } %>
That seems like alot of opening and closing tags to me!
Other view engines in the MVC contrib have a means of spitting to screen with out opening and closing the script tags using standard keyword such as "print, out, echo" i.e. (brail example):
<%
for element in list:
output "<li>${element}</li>"
end
%>
Now, I said this may seem trivial, but it just seems more readable this way. So what are the advantages of MS having this syntax, and not providing a output method?
Cheers, Chris.

Consider something like this, instead:
<% foreach(var Person in People) {
Response.Write(Person.Name);
} %>
I believe that'll work. (Although I haven't tested it; I've only just begun with MVC and don't have the toolset here at the office.)
EDIT: I apparently missed the actual question ... :)
Microsoft does provide an output method, but didn't provide a syntax like the one you describe. The output method is Response.Write(). I can't answer this directly (I believe you'll need to check with Scott Hanselmann over at MS :)), but I think they didn't want to complicate scripting by adding yet-another-language for us to learn; I think they wanted to leverage the languages (C#, VB, etc.) which developers already knew.
EDIT #2: I placed the following in a comment, and in retrospect (for completeness), it should be part of the answer.
If you head over to the Learn MVC site on ASP.NET, in the view tutorial (that's the link), you'll see the following paragraph:
Since you call Response.Write() so
often, Microsoft provides you with a
shortcut for calling the
Response.Write() method. The view in
Listing 3 uses the delimiters <%= and
%> as a shortcut for calling
Response.Write().
Essentially, <%= %> is the accepted shortcut for Response.Write, and you therefore can use the full Response.Write method anywhere you'd use <%= %>.

My answer is based on personal XP with MVC4 cshtml - you can use:
#Html.Raw("SomeStringDirectlyInsideTheBrowserPageHTMLCode")
This renders the (dynamic) string at its position unlike Response.Write(MyString) which as far as I've noticed always renders the string at the begining of the browser-page.
Note that the HTML tags rendered by #Html.Raw(MyString) cannot be checked by the compiler. I mean: #Html.Raw("<div ....>") cannot be closed by mere </div> because you will get an error (<div ....> is not detected by the compiler) so you must close the tag with #Html.Raw("</div>")
P.S.In some cases this doesn't work (for example it fails within DevExpress) - use ViewContext.Writer.Write() or ViewContext.Writer.WriteLine() instead.

What you're looking for is probably a different View engine -- they each handle embedded code like that in their own way. Check out NHaml, an ASP.Net port of Rails' Haml engine.
Some more view engines to look at: Brail,
NVelocity

Thanks guys,I dont specifically want to switch view engines, though I will take time to look at the other avaliable. I am sure you can understand that most MS development houses dont touch anything but MS branded technology so I just wanted to know if there was a way to do this with the default view engine. Or if not, why not? Is there a reason, if not where could I suggest the default view compiler add such a keywork.
John- I believe that Response.Write(Person.Name) will just render the string to the top of the page, before any other output. Not 100% on that though, ill give it a bash.
Edit:
Apparently, Response.Write(Person.Name) works as suggested. Well that was easy. Thanks :-) John.

I've heard they're working on improving this for ASP.Net 4 via client templates.

Another option other than Response.Write would be to write XHtml with XSL transformations

Related

ASP.NET MVC, different of Razor syntax and ASP.NET syntax?

The advantage of razor syntax over asp.net syntax just using on short tag "#" instead of "<%= %>"??
Is it any other feature or data binding method razor can do, but asp.net syntax not?
Razor is pretty cool, it can often detect if you are writing HTML code in your code blocks. So say that you are declaring a big block of C# code, by using #. You then write a foreach-loop in that, and write some HTML that should be echoed out. In ASP.net markup, you'd have to end the C# code block with %> and then reopen it with <%. Razor, on the other hand, can detect when you are writing HTML and does that for you. It will also detect where you put the bracket that closes the loop, without you having to put it within <% %>. Very handy, and a timesaver.
For more information: Click click.
#section, #model, IntelliSense, inline C#, what else?

Why is this consider bad practice? or is it? (ASP.Net)

Would this code be considered bad practice:
<div id="sidebar">
<% =DisplayMeetings(12) %>
</div>
This is a snippet of code from the default.aspx of a small web app I have worked on. It works perfectly well, runs very fast, but as always, I am aware of the fact that just because it works, doesn't mean it is OK.
Basically, the DisplayMeetings subroutine outputs a bunch of formatted HTML (an unordered list actually), with no formatting, just the requisite html, and then my CSS performs all the necessary formatting.
The data for generating the list comes from an SQL server database (the parameter controls how many rows to return) and I am using stored procedures and datareader for fast access. This keeps my front-end extraordinary simple and clean, imho, and lets me do all the work in VB or C# in a separate module.
I could of course use a databound repeater (and probably 6 or more other methods) of accomplishing the same thing, but are they any better? Other than loosing the design-time features of VS2010?
The only thing "wrong" with your approach is that it mixes code and display, which you typically want to avoid wherever possible. If you have to have a procedurally generated portion of HTML (because it's just that difficult to do with controls, or whatever), create a control responsible for generating that HTML and embed it in the larger page/control that contains it.
is the "wrong" part, that the subroutine is returning HTML, or is it that I have a code-snippet executed from within the HTML markup?
Both, in a way. And also neither.
There's nothing directly "wrong" with using <%= foo %>; if there were, it wouldn't be part of the framework. What's "wrong" with it is that it sets up a two-way dependency that you don't necessarily want. Your HTML markup is dependent on and has to know about the code-behind. It has to call the method, which in turn is dedicated to the markup and nothing else. If you want to make changes to your output, you may have to change the method, the markup, or both.
What I'm trying to say is that what you're doing makes your code less maintainable, less flexible to modify the next time you have to open the hood.
If it's the only way to solve a problem, then it's the only way, and there's nothing wrong with that. But it's something that should be avoided, in general, if possible.
How would I have done it? That depends on the situation, frankly. If I could have used a standard component with databinding, I'd have done that. That is always preferred. If the HTML was just too complex to use a component, I'd use a Literal control as a placeholder for the markup, and generate the markup in a separate component--likely a User Control.
The point is that the markup knows nothing about the method used to generate the other markup, it just says "something goes here" and relies on its code-behind to handle deciding which markup to put in there.
It's not something I'd do. I'm not a fan of using <%= %> in Webforms. Sadly, it's also common practice.
What I'd probably do instead is a build a user control to represent the markup I wanted and put that on the form. This has the advantages of making the element more re-usable, testable, and gives you more control over where in the page life cycle the code is called.
A databound repeater can make it somewhat simpler to modify your html when you need to change the layout. It is also nice if you have separate people who work on html vs people who work on the server side code.
My usual rule is to use a repeater for any even slightly complex html. And I do not call methods from my aspx/ascx file - I only insert the values of a protected string variable which I have populated in the code. However, these are personal preferences, and I don't see anything really wrong with what you are doing.
Your code (without seeing it) will likely be faster than a repeater, since there is no data binding involved, but it probably wouldn't be a huge thing unless the page is very, very popular.

Alternatives to ASCX User Control without a server-side form?

I've got an ASP.NET 3.5 Web Forms application in which a large chunk of code needs to be duplicated between a few different pages. Sounds like the ideal candidate for a user-control right? Problem is, this cannot be contained within a <form runat="server"> because it contains a client-side form of it's own.
There are no runat=server controls or postbacks or anything that really need that webform - think of it just as a chunk of HTML with a few basic <% %> tags. I'd just want to set a property on the control when it's loaded, so that it knows what to output. This is purely an exercise to make the code easier to maintain.
Before I resort to using an oldskool <!--#include-->, is there some better way of doing this?
You can still use a normal user control. Just don't rely on viewstate and postbacks and you shouldn't have any problems.
<%=Response.Write(File.ReadAllText(Server.MapPath("~/includes/filename.ext")))%>
Something along those lines, anyway.
Edit: Same functionality as a server side include, but if I'm not mistaken, enabling the SSI syntax requires an IIS change, where as this wouldn't.
Edit 2: I didn't see the note that your include contains asp.net code. This would obviously only work for client side code only. My mistake.
You can have as many form controls as you want but only one can have runat="server".
Some other techniques:
http://webproject.scottgu.com/CSharp/UserControls/UserControls.aspx
http://weblogs.asp.net/scottgu/archive/2005/08/28/423888.aspx
I'd still make it a control. The <% %> stuff could be labels/literals for more flexibility, and as soon as you get done saying there are no postbacks needed, you'll need them. Best to set up the other pages to include it as a control now for easier changes later. Heck - you could even take advantage control-level caching!

ASP.NET - Inline vs. Code-Behind

I realize that by asking this question, I could have started the apocalypse, but a colleague of mine uses a lot of inline coding in their aspx pages, where as I prefer using the code-behind.
Is there a right and a wrong way here?
Not unless your coding standard says otherwise.
IMO code-behind helps separation of concerns, so I prefer that, but sometimes just dealing with one file is nice too.
Code-behind is the more traditional and logical place. If it works, it works, but I can't stand doing it in the aspx.
I made the exact post a while back:
OnDataBinding vs Inline: pros, cons and overhead
I prefer the code behind. I usually have a #region area for all the databinding stuff. It allows for people skilled in HTML / CSS to tweak the HTML and all they have to know is what basic controls to use and to define the OnDataBinding event in the control's definition. They can move things around and do whatever and have no knowledge of what it actually takes to get the data into that databind as it might not be as simple as just a basic 'Eval("something");.
Well, there's inline code, and then there's inline code. If you have a script block at the top for you page_load, that's just fine. But if you're mixing a lot of bee-stings (<% %>) in with the markup, you'll eventually start to have trouble when those bee-stings don't work as you would like with other server controls.
Personally I prefer compile errors to run-time errors so I put all my logic in code behinds.
Occasionally when I just need a value to show up on the page I'll put <%=SomeValue%> but even then I much prefer to create a label and set it.
I want to make sure i understand the question - by in-line, do you mean snippets like
<a><% some.asp.net.code %></a>
or do you mean one vs. two files for each page:
page.aspx
page.aspx.cs
?
Because I am NOT a fan of what I call the 'embedded' code in the first example but I DO prefer code and markup in the same file with a < script runat="server">
There is no right/wrong with either of this.
You can write some code inline & some of it should be written in code-behind. It can't be absolute. Depends on how readable/maintainable it becomes when you write it on the other side.
EDIT: As it is said, write code for human & incidentally for the compiler.
I tend to use the code-behind since it is the only way for WPF and I try to stay consistant and it feels more natural. But thats subjective.

Performance of asp.net page with code and design in the same page

I have a query that hit my mind when I was adding an asp.net web page in a project. Normally we place the server side code in the codebehind file. Could there be any improvement in the server side processing if we place both the code and the page design markup in the same page? I am referring to the practice like this:
<div>
<%if (ViewState["user-id"] != null)
{%>
<div>Hi, You are welcome.</div>
<%}
else
{%>
<div>Hi, please login or register.</div>
<%} %>
</div>
If we use separate codebehind file, we would do all these in the page load event and make div elements visible, invisible according to the test. We could even have only one div in the design page and set its inner text accordingly. Any suggestions?
Interesting question.
If this runs any faster, you're going to have to offset this against the cost of maintenance on your pages. This style of coding was commonplace during the Classic ASP era. The markup can be a total nightmare to maintain, particularly if your coding team and design team are different people.
My suggestion? Only use inline stuff when you want to spit out a value in tie-fighter syntax.
<%= Greeting %>
Use the codebehind for anything that involves control or loop structures. I'd genuinely be interested in whether in-line is faster than codebehind, but any speed increase you might gain is going to be downright negligible compared to the hassle you'll have maintaining software built using this approach.
Paul is totally right...This will be a nightmare to maintain. Do NOT do this. :|
To answer the original question... No, this will not give you any speed increase. At best, it's break-even. But it could actually create a performance hit. Think about what this code is actually doing on the back end, in the ASP.NET engine and it should be apparent.

Resources