开发者

Best practice for setting output programmatically?

开发者 https://www.devze.com 2023-03-26 20:52 出处:网络
I have been working with ASP.Net for some time, but I have a question about the very basic way of outputting content like an error message.

I have been working with ASP.Net for some time, but I have a question about the very basic way of outputting content like an error message.

I see two major alternatives:

  • Use a user control and set the content in the codebehind.

    <asp:Literal id="litError" runat="server" />
    

    Codebehind:

    litError.Text = "You're doing it wrong!";
    
  • Set a member variable in the codebehind and output it.

    protected string errorMessage;
    ...
    if(error)
       errorMessage = "You're doing it wrong!";
    

    ASPX:

    <%: errorMessage %>
    

Which way is best practice? Is it just personal preference, which method t开发者_开发百科o use? I know that there are circumstances under which one or the other method might not be available, but I am talking about cases where both would work.

What are the advantages and drawbacks? Is there a third way which should be preferred?

I always used the usercontrol method, but with the new nugget syntax introduced in ASP.Net 4.0 I start to think I am maybe on the wrong track.


I don't think there is a correct way to do this, they are both perfectly valid options. They both end up as properties on the page class. The literal control is a server control so there are properties and methods that may be useful to you as a page developer, but that would be on a case by case basis.


I think it just comes down to preference. Personally, I don't like mixing inline code with code behind, so I always (where possible) prefer to use the code behind for programmatic output. From a business perspective, I think the mixing of inline and code behind undermines consistency and makes the code harder to learn for the next person. I will always vote in favor of consistency.

That's just my two cents. Hope it helps.


I think it largely boils down to preference. There is no real difference between the two popular methods except syntax.


There is a slight difference between the two as one runs in the code behind and populates a server control and the other is a reference to a method of the code behind. Depending on your coding techniques, it is possible that there can be a difference when the code is run. However, as far as best practices? Like everyone else's answer, it comes down to preference.

0

精彩评论

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