我使用带有 .NET 的 webforms/masterpage。
我的页面中有许多 Web 用户控件。
有没有一点我可以在一些“字符串”中进行一些替换?
就像,如果 .NET 生成:
<div>Hello my Name is Marco</div>
将其更改为:
<div>Hi, my Name is Luca</div>
可能吗?或者我每次获取这些数据(从数据库)并执行 response.write 时都需要创建我的特定实用程序?
The ASP.Net WebForms approach would be to use a label control and set the name in the code behind.
So your aspx file would contain
<div>Hello my Name is <asp:Label id="NameLabel" runat="server"/></div>
And your code behide file ie the aspx.cs would contain
NameLabel.Text = "Luca"
And if your looking to implement something dirty its possible to modifying the HTTP response using filters. This article explains in better detail. http://www.4guysfromrolla.com/articles/120308-1.aspx But I wouldn't recommend using this.
您应该能够编写一个IHttpModule
并将其连接到PreSendRequestContent
事件,并在此处进行替换。看看这里提出的解决方案:http ://www.tek-tips.com/viewthread.cfm?qid=1149673
使用这种技术,您可以在不重新编译的情况下更改显示给用户的消息,同时保持数据、逻辑和 ui 关注点分开。它并不“简单”,但它很干净。
免责声明:不是使用 IDE 编写的
网页表格
<div><asp:Literal id="litHelloMessage" runat="server" text="<%=GetHelloMessage() %>" />
<asp:Literal id="litName" runat="server" text="<%=User.Name %>"/>
代码背后
public class MyPage : Page
{
public User User { get; set; }
public void Page_Load()
{
// logic to fetch the user from your persistence store
// e.g. User = MyUserRepo.Fetch(uid);
// Important
DataBind();
}
public string GetHelloMessage()
{
// this is straight forward, alternatively you could have some logic here to
// derive which which message is shown to the user
litHelloMessage = GetLocalResourceObject(User.MessageResourceKey).ToString();
}
}
资源文件(App_LocalResources/mypage.resx)
Key Value
"HelloMessage" "Hello my Name is"
"HiMessage" "Hi, my Name is"
用户类
public class User
{
public string Name { get; set; }
public string MessageResourceKey { get; set; }
}
样本数据
Name MessageResourceKey
"Marco" "HelloMessage"
"Luca" "HiMessage"
What you need is a template engine. This is a good start from wikipedia http://en.wikipedia.org/wiki/Template_engine_(web)
Or the View part of the MVC concept as others pointed out.
There are different ways of implementing a template engine and many more ready to use ones.