Best way to access properties of my code behind class from the markup in ASP.NET

前端 未结 5 1282
攒了一身酷
攒了一身酷 2020-12-14 02:50

This might be a really dumb question but I\'m learning .NET, so I\'m quite clueless...

Let\'s say I have two files default.aspx and the associated default.a

5条回答
  •  囚心锁ツ
    2020-12-14 03:28

    You can do any coding that you'd like to do directly in the ASPX file, rather than using codebehind. So, to accomplish what I think you want to do, you would have...

    
    
    <% var MyObject = new MyObject();
       Response.Write(myObj.Awesome()); %>
    
    
    

    However, this is really not recommended. Codebehind is the suggested "best practice" way of doing things, because this separates your code from your markup, which is fundamental in any good architecture. I would recommend using something like what John Saunders posted in order to avoid databinding, but you should really consider manipulating your controls in the codebehind using the lifecycle events rather than outputting object properties directly to your HTML. For example, if you were trying to output some text, then do something like

    var literal = new LiteralControl(myObject.Awesome());
    myPanel.Controls.Add(literal);
    

提交回复
热议问题