简体   繁体   中英

What is the best way to databind Web Form controls to linq objects?

I have a typical object (it comes from Linq but it could have been create manually):

public class Person
{
  public string FirstName{get; set;}
  public string LastName{get; set;}
  public int Age{get; set;}
}

And I have a Web Form where users enter this data:

<asp:TextBox runat="server" ID="FirstName"></asp:TextBox>
<asp:TextBox runat="server" ID="LastName"></asp:TextBox>
<asp:TextBox runat="server" ID="Age"></asp:TextBox>

How do I bind the data from the Control to the class? I could do this:

Person person;
person.FirstName = FirstName.Text;

but is there something better where the class or Linq just sucks in the Control values automatically?

ASP.NET MVC would both create these forms and fill these values in on postback for you. Here is an example where both are done.

DataClassesDataContext db = new DataClassesDataContext();

//Some Event

protected void btn_Submit_Click(object sender, System.EventArgs e)
{

   Person NewP = new Person();
   NewP.FirstName = FirstName.Text;
   NewP.LastName = LastName.Text;
   ...

   db.Persons.InsertOnSubmit(NewP);

   try 
   {
      db.SubmitChanges();
   }
   catch (Exception ex) 
   {
      Response.Write(ex.ToString);
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM