ASP.NET MVC, different of Razor syntax and ASP.NET syntax? - asp.net

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?

Related

Optimizing and organizing ASP.NET content

I have a new ASP.NET Web Forms project that was started about 6 months ago. Being as how the project is still fairly new and in its infancy, this hasn't been much of a problem till recently.
The application is an ASP.NET Web Form application with a C# and SQL Server back end and an HTML5 and jQuery front end. The application is mostly ajax powered with very little post backs. It consists of mostly jQuery ajax calls to C# WebMethods.
The problem I am running into is some of my aspx pages are over 50kb in size with all the javascript and jQuery that is in the aspx page. I would like to move a lot of this javascript and jQuery code into separate files, but most of it consists of code that use the aspx <%= %> tags, which makes moving it a difficult (if not impossible) task.
It is getting tedious to find things in the code. I am wondering if there is a way to optimize the code (by somehow reducing the size of the aspx file) and if there is a good way to keep all this jQuery and javascript organized better so that finding things are a little bit easier? Also, is there maybe a javascript minifier that will minify the javascript inside an aspx page?
Any help would be appreciated!
Since you are using AJAX, I'm assuming you're using HTML markup, not any of the web controls. If so, one thing you can do is trun of ViewState in the aspx page. I was in the same position a few years ago, and decided to switch the Asp.net MVC. I would recommend you look into that. It gives you a much better development model, with minimal overhead.
Also, is you JS/CSS minified? I'm still confused about why "...but most of it consists of code that use the aspx <%= %> tags, which makes moving it a difficult (if not impossible) task."
WebForms, like MVC, also now supports bundling and minifications of JS files, check this out: http://blogs.msdn.com/b/rickandy/archive/2012/08/14/adding-bundling-and-minification-to-web-forms.aspx
Update: As OP pointed out, for .Net 3.5, you can use http://getcassette.net/ for bundling and minification.
to avoid using <% %> in your js to be able to reference your controls you can set the ClientIDMode to "static", that way the ID you set for the controls is the one that will be rendered and in js you can reference the control with something like
asp.net
<asp:DropDownList ID="ddlStateName" runat="server" ClientIDMode="static"></DropdownList>
jquery
$("#ddlStateName").val();

Using underscore templating with ASP.NET controls

I am trying to use underscores templating system in my project. Now the issue is that we have a lot of server side (ASP.NET) controls as well that I would like to use. Is there any way to use the ASP.NET controls together with underscore templates?
I tried simulating a template as an aspx page to get the rendered html from there and then use the result but that seems like an overkill.
I am pretty new to templating so I have no idea about what to expect.
EDIT:
What I meant was, is there any way I can have e.g. an ASP.NET button inside an underscore template?
The issue isn't with ASP.NET Controls (which use the runat="server" attribute), but with ASP.NET's Render function syntax <% %>.
See this earlier QA: How to use underscore/javascript templates in ASP.Net MVC views the solution is to configure underscore.js to use a different delimiter:
This:
_.templateSettings = {
interpolate: /\{%=(.+?)%\}/g,
escape: /\{%-(.+?)%\}/g,
evaluate: /\{%(.+?)%\}/g
};
...will let you use {% %} as delimiters instead of <% %>.
I just thought that it might help someone. One of the controls I wanted to use was a devexpress grid in my view. Now I could have done a "view source" on the grid and copied the rendered html to generate the view. However, I decided to create an aspx page and did an ajax call to the aspx page and displayed the resultant html in the view. I was hoping there would be a better way to do this.

Which is better to initialize HTML control values: Javascript or inline server tags?

Which is better/more maintainable, using Javascript to initialize the values of the different HTML controls or writing inline <% %> tags?
The current page I am writing has many HTML controls and I'm afreaid that putting inline ASP would make it too unmaintainable.
Well... using JS to populate the controls with values will make the whole solution useless in JS-free environments. This is not what the webdev community calls unobtrussive.
As you donĀ“t define better any better (!) I would say go for the inline rendering.
If you really have millions (I really doubt this number) of HTML Controls in your page I would say you need to get back to the drawing board and re-architect the solution.
You are going to have the same problem regardless of the method: maintainability.
I have some legacy forms that need to remember some fields between calls, so I have a lot of code that might be a little ugly, but if you stick to a standard, doesn't get too messy.
<label for="email<%=i%>">E-Mail<% if required then %> (*)<% end if %>:</label>
<input name="email<%=i%>" id="email<%=i%>" type="text" value="<%=Trim(request.form("email"&i))%>" />
The problem is that it involves a lot of copy paste when having to add a new control. You could make a function to build it and keep the code duplication to a minimum.
<%= BuildHTMLInputControl("email"&i, "text", "E-Mail", true) %>
' Response: <label for="email1">E-Mail (*):</label><input name="email1" id="email1" type="text" value="Previous Value" />
I haven't done something like this, because it hasn't been a concern yet in the small forms that I've done this.
The advantage of this is that the fields are populated onload, there is no flashing of content and you are really friendly to non-Javascript users, something that you should be.
The only difference would be that with javascript youd have a lot of document.getElementById() at the beggining (or rather end) of the document, that increases the HTML file size (which might be a concern) and could not populate the fields instantly.
If you've really got loads and loads of HTML controls in an ASP.Net page, you might have to rethink your design. Why aren't you using server controls?
However, you can always use the runtat="server" attribute on HTML elements to effectively turn them into server-side controls. You can then work with them in much the same way as ASP.Net controls. You may want to watch out for extra Viewstate being added, though.
What is better/more maintainable,
using Javascript to initialize the
values of the different HTML controls
or writing inline <% %> tags?
I wouldn't do it either way. That sounds like old-style ASP, or maybe PHP or JSP-type logic.
The ASP.NET model is to use controls on the page, and then to set the values of those controls either from code-behind or in-line code, possibly using some type of data binding. Separating the display logic from the data is much, much easier to maintain.

Microsoft MVC "echo/print/output" etc

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

Duplicate html in a ASP.NET project

I have some HTML that will need to be duplicated in a number of places. If I externalize this to a text file and include it in the ASPX page, it would work but I will need to pass a parameter to this HTML (ClientID)
Without having to create a User control, is there a lighter way of doing this?
I would use a master page for this. Depending in the version of the framework(2.0+) Nested Master Pages are also an option.
You could just have a raw aspx file with the HTML inside:
<%
If (Request.QueryString["ClientID"]) {
// Do Something
}
%>
<p>HTML File Contents</p>
Then you could either server-side include the file or server.execute the file.
You may want to clarify how you pass a ClientID to "HTML", because it sounds like you're doing server-side processing to generate your HTML, which is a classic case of Ajax. I would recommend using JQuery to achieve this.
Perhaps standard #Includes still work, but TBH I haven't found any downside to master pages (as yet). This is what they were designed for.

Resources