2012-11-14 2 views
0

나는 각 행마다 체크 박스와 성을 포함하는 간단한 리피터가 있습니다. 또한 데이터베이스에 새 전체 이름을 추가하는 "이름 추가"단추가 있습니다.체크 박스에서 정보를 잃지 않고 새 행을 리피터에 추가하는 방법

사용자가 몇 가지 체크 박스를 확인하고 다른 이름을 추가하기로 결정했다면 이미 체크 된 체크 박스의 정보를 잃지 않고 리피터에 새 이름을 추가 할 수 있기를 원합니다.

나는 자바 스크립트 코드가 트릭을 할 수도 있다는 것을 이해하고 어떻게 접근 하는가? 어떻게해야합니까?

미리 감사드립니다.

p.s. js와 관련하여 olny가 아니라 어떤 조언도 듣게되어 기쁩니다.

+1

당신은 더 정확해야한다을 줄 것이다 희망 , 샘에게 줄지도 몰라. 당신이 경험하는 이슈를 이해할 수 있도록 도와주세요. –

답변

1

는, 아주 예쁜하지 빠른 솔루션을하지만 일을 얻을. 그것은 몇 가지 새로운 아이디어


당신에게하여 default.aspx.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

namespace RepeaterCheckbox 
{ 
    public partial class _Default : System.Web.UI.Page 
    { 
     [Serializable] 
     public class Person 
     { 
      public int Id { get; set; } 
      public string Name { get; set; } 
     } 

     List<Person> personsFromDatabase 
     { 
      get { return (List<Person>)ViewState["persons"]; } 
      set { ViewState["persons"] = value; } 
     } 

     //here we will store our person selection state 
     Dictionary<int,bool> personSelectionState 
     { 
      get { return (Dictionary<int, bool>)ViewState["data"]; } 
      set { ViewState["data"] = value; } 
     } 

     protected override void OnLoad(EventArgs e) 
     { 
      if (!IsPostBack) 
      { 
       #region Test data 
       personsFromDatabase = new List<Person>{ 
        new Person { Id = 1, Name = "Paul", }, 
        new Person { Id = 2, Name = "Tom", }, 
       }; 
       #endregion 

       Bind(false); 
      } 
      base.OnLoad(e); 
     } 

     void Bind(bool isPostback) 
     { 
      if (!isPostback) 
      { 
       //initialize person selection mapping 
       personSelectionState = new Dictionary<int, bool>(); 
       foreach (Person person in personsFromDatabase) 
       personSelectionState.Add(person.Id, false); 
      } 

      //map persons to anonymous type that will help us define necessary values 
      rpPersons.DataSource = personsFromDatabase.Select(x => new 
      { 
       Id = x.Id, 
       Name = x.Name, 
       //get stored selection state for person 
       Selected = personSelectionState[x.Id], 
      }); 
      rpPersons.DataBind(); 
     } 

     protected void btnAddPerson_Click(object sender, EventArgs e) 
     { 
      //update selection states 
      UpdateSelectionStatuses(); 

      if (!String.IsNullOrEmpty(txbName.Text)) 
      { 
       //add new person 
       personsFromDatabase.Add(new Person 
        { 
         Id = personsFromDatabase.Count +1, 
         Name = txbName.Text, 
        }); 

       //add status mapping for new person so there is no error on postback binding 
       personSelectionState.Add(personsFromDatabase.Count, false); 

       //Refresh data on page, to see new person 
       Bind(true); 
      } 
     } 

     void UpdateSelectionStatuses() 
     { 
      //loop through all items 
      for (int i = 0; i < rpPersons.Items.Count; ++i) 
      { 
       RepeaterItem repeaterItem = rpPersons.Items[i]; 

       //find checkbox for item 
       var checkbox = (CheckBox)repeaterItem.FindControl("chbSelected"); 
       if (checkbox != null) 
       { 
        //get our custom attribute 
        int id = int.Parse(checkbox.Attributes["personId"]); 

        //update stored checkbox status 
        personSelectionState[id] = checkbox.Checked; 
       } 
      } 
     } 

     protected void rpPersons_ItemDataBound(object sender, RepeaterItemEventArgs e) 
     { 
      if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 
      { 
       var item = e.Item.DataItem; 

       var checkbox = (CheckBox)e.Item.FindControl("chbSelected"); 
       if (item != null && checkbox != null) 
       { 
        //get person id from our helper anonymous type 
        System.Reflection.PropertyInfo[] anonymousTypeProperties = item.GetType().GetProperties(); 
        int id = (int)anonymousTypeProperties.Where(x => x.Name == "Id").FirstOrDefault().GetValue(item, null); 

        //set custom attribute on checkbox to map checkbox with person 
        checkbox.Attributes["personId"] = id.ToString(); 
       } 
      } 
     } 
    } 
} 

Default.aspx를

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="RepeaterCheckbox._Default" %> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
<title></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
     <div> 
      <asp:Repeater runat="server" ID="rpPersons" OnItemDataBound="rpPersons_ItemDataBound" > 
       <ItemTemplate> 
        <p> 
         <asp:CheckBox ID="chbSelected" runat="server" AutoPostBack="false" Checked='<%# DataBinder.Eval(Container.DataItem, "Selected") %>' /> 
         <asp:Label ID="lblName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>' /> 
        </p> 
       </ItemTemplate> 
      </asp:Repeater> 
      <div> 
       <asp:TextBox ID="txbName" runat="server" /> 
       <asp:Button ID="btnAddPerson" runat="server" Text="Add person" OnClick="btnAddPerson_Click" /> 
      </div> 
     </div> 
    </form> 
</body> 
</html> 
+0

새 폼에 넣을 때 효과적이지만 마스터 페이지와 관련된 폼에 해당 코드를 삽입하면 폼이 컴파일되지 않습니다. 어떤 아이디어? – Yanker

+0

일부 코드를 게시 할 수 있다면 좋겠지 만 masterpage가 아닌 asp 페이지 (컨테이너)에 리피터를 배치해야한다고 생각합니다. 사이트 구조에 대해 잘 모르는 경우 진단하기가 어렵습니다. – pawciu

+0

문제는 "Default.aspx.cs"코드에서 "ViewState"를 "Session"으로 변경해야한다는 것입니다. 그리고 그것은 어떤 이유로 든 매력으로 작용합니다. – Yanker

1

어떻게 접근 하느냐에 따라 다릅니다. Ajax 업데이트 패널에서 asp.net repeater를 사용하고 있습니까? 새 항목을 추가 할 때 이러한 방식으로 각 클릭 이벤트에서 확인란 값을 저장할 수있는 경우 컨트롤은 업데이트 된 값으로 다시 바인딩됩니다.

당신이 THIE 포스트는 도움이 자바 스크립트 클라이언트 측 사용하려는 경우 여기 How to add rows to a repeater in client side

관련 문제