开发者

What is proper ASP.NET style?

I'm just starting to do web pages in ASP and all of the code just feels... messy.

<% if (new Random().NextDouble() < 0.5) { %>
    <asp:Image ID="image" runat="server" ImageUrl="~/1.jpg" />
<% } else { %>
    <asp:Image ID="image" runat="server" ImageUrl="~/2.jpg" />
<% } %>

Currently, I have a very basic page that is light on content, but eventually I am going to have to add logic and more display elements to this. So I come to you, SO.

First, how would I clean up this small segment of code? Second, what do I need to know going forward?

Edit: The asp:Image tags were generated from VS2008, and then I added the if blocks based 开发者_如何学Con what I found online. I have plenty of experience with C#, but absolutely none with ASP, so if there's more subtleties about this code that I'm not grasping, by all means enlighten!


In the markup:

<asp:Image ID="image" runat="server" />

In the code-behind:

...
if (new Random().NextDouble() < 0.5)
{
    image.ImageUrl = "~/1.jpg";
}
else
{
    image.ImageUrl = "~/2.jpg";
}


In your specific case,

<asp:Image ID="image" runat="server" 
           ImageUrl='~/<%= new Random().Next(1,3) %>.jpg' />

But in general, choosing to do things in code behind or in the markup is a choice you have to make. You may like Razor, a new way of doing in markup code. I haven't tried it yet myself, but it looks a bit cleaner.


what about an inline if statement. This allows you to manipulate the imageUrl in 1 line instead of 5

    <asp:Image ID="image" runat="server" ImageUrl='<%= (new Random().NextDouble() < 0.5) ? "~/1.jpg" : "~/2.jpg" %>' />

As for your second question.. There's a lot to .NET and you need to know a decent chunk of it going forward. Look into some design patterns (MVC is my favorite)


ASP.NET WebForms is a bit messy. That was one of its drawbacks, along with ViewState and the rather convoluted eventing model. If you wish to use a cleaner platform for developing web sites, I recommend ASP.NET MVC.


Better still, try to have as little code as possible in the markup of the page and set the ImageUrl of image in the page load event or another method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜