开发者

Cleaner way to write inline c# in .aspx page

开发者 https://www.devze.com 2023-02-04 15:01 出处:网络
For reasons that are probably not worth mentioning in this post, I have decided to stop using ASP.NET controls and simply use regular HTML controls for my .aspx pages. As such, to dynamically generate

For reasons that are probably not worth mentioning in this post, I have decided to stop using ASP.NET controls and simply use regular HTML controls for my .aspx pages. As such, to dynamically generate HTML, I use c# inline to the .aspx to do what I need to do.

For example: this .aspx snippet shows how I am dynamically creating a <select> element where the <option> elements are driven by looping through a generic list of objects.

<select name="s">
<option value="-9999">Select an entity...</option>
<% foreach (MyEntity e in this.MyEntities)
 {%>
<option <% if (MyEntityInScope.ID == e.ID)
 { %>selected<%} %> value="<%= e.ID %>">
<%= e.Name%></option>
<%} %>
</select>

Functionality-wise, I prefer this met开发者_StackOverflow中文版hod of creating HTML (I feel more in control of how the HTML is generated vs ASP controls). However, syntactically (and visually), I think it's cumbersome (and ugly).

Is there a "better" way (another syntax) to dynamically generate HTML w/out resorting to using ASP.NET controls?


Why don't you put your logic into a method and call this method?

string GetEntityList()
{
// ...
}

<select name="s">
<option value="-9999">Select an entity...</option>
<%=  GetEntityList() %>
</select>


A common approach is XML through XSLT. That is, your code assembles an XML document, loads a suitable XSLT transform and sends the result.


A utility method that returns an HTML string can help with that, similar to the HTML helpers in ASP.NET MVC.

0

精彩评论

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