ASP.NET:添加控件客户端 [英] ASP.NET: adding controls client-side

查看:99
本文介绍了ASP.NET:添加控件客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个网页形式(想象一下一个简单的只有文本框和一个提交按钮),我想,让用户更文本框dynamiccally添加到通过JavaScript的形式,什么是处理的最佳方式要求服务器端?

If I have a page with a form (imagine a simple one with just TextBoxes and a submit button) and I want to allow the user to dynamiccally add more TextBoxes to the form via javascript, what is the best way to handle the request server side?

例子:我已经作出类似下面的页面:

Example: I have a page rendered like the following :

<input type = "text" id = "control1" name = "control1" />
<input type = "text" id = "control2" name = "control2" />
<input type = "text" id = "control3" name = "control3" />
<input type = "submit" />

用户触发一些JavaScript和页面原来这样的:

The user trigger some Javascript and the page turns out like:

<input type = "text" id = "control1" name = "control1" />
<input type = "text" id = "control2" name = "control2" />
<input type = "text" id = "control3" name = "control3" />
<input type = "text" id = "control4" name = "control4" />
<input type = "text" id = "control5" name = "control5" />
<input type = "submit" />

这是什么来处理这种情况的最佳方式,或者,更一般地,与动态产生的输入客户端和服务器端(工作例如,如何生成它们服务器一侧,也就是说,从一个数据库中采取了一些数据开始)?

What is the best way to handle this kind of situation, or, more generally, working with dynamically generated input both client and server side (eg, how to generate them server side starting from, say, some data taken from a database)?

推荐答案

我已经做similiar事情到了这无数次。我的preferred方法通常是使用一个中继器和一个按钮(标记添加)的UpdatePanel内。

I have done similiar things to this numerous times. My preferred approach is usually to use a Repeater and a Button (labelled Add) inside an UpdatePanel.

有关在code中的 Button_OnClick 事件背后做类似的东西来此;

For the Button_OnClick event in your code behind do something similiar to this;

 Loop through the Items collection of the Repeater
 Use item.FindControl("txtUserInput") to get the TextBox for that item
 Save the text of each input to List<string> 
 Add an empty string to the the list
 Databind the repeater to this new list

下面是一些例子code;

Here's some example code;

<asp:Repeater runat="server" ID="rptAttendees">
	<ItemTemplate>
		<asp:TextBox runat="server" ID="txtAttendeeEmail" Text='<%# Container.DataItem %>'></asp:TextBox>
	</ItemTemplate> 
</asp:Repeater>



protected void btnAddAttendee_Click(object sender, EventArgs e)
{
    var attendees = new List<string>();

    foreach (RepeaterItem item in rptAttendees.Items)
    {
        TextBox txtAttendeeEmail = (TextBox)item.FindControl("txtAttendeeEmail");
        attendees.Add(txtAttendeeEmail.Text);
    }

    SaveAttendees();
    attendees.Add("");
    rptAttendees.DataSource = attendees;
    rptAttendees.DataBind();
}

这篇关于ASP.NET:添加控件客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆