2011-07-15 8 views
0

私は3列の1テーブルを持つSQLデータベースを持っています。documentID, documentTitle, documentBodyテキストをSQL Server 2005データベースに配置します

2つの入力を持つaspxページがあります。本文のタイトル1と送信ボタン1に1つです。

私は入力フィールド内のテキストをデータベースの新しい行に格納するだけですか?私は簡単な具体的な答えを見つけることができず、それが複雑であるという方法はありません。

<form id="form1" runat="server"> 
<div style="width: 800px; margin-top: 40px;"> 
    <p style="text-align: left"> 
     Title</p> 
    <p> 
     <input id="inputTitle" runat="server" type="text" style="width: 100%; padding: 6px; 
      font-size: large" /></p> 
    <p style="text-align: left"> 
     Body</p> 
    <p> 
     <textarea id="inputBody" runat="server" style="width: 100%; height: 400px" cols="22" 
      rows="66"></textarea></p> 
    <p> 
     <input id="save" type="submit" onclick="submit_onclick" value="Save as the newest version" /><span> or 
     </span><a href>Cancel</a></p> 
</div> 
</form> 
+0

SQL Server Management Studio 2005. Visual Studio 2010。 – bluetickk

答えて

0

使用ASP.NETサーバーご入力のコントロール、代わりの<input>

protected void SaveDetails(object sender, EventArgs e) { 

    using (var conn = new SqlConnection("Data Source=YourServerName;Initial Catalog=YourDatabaseName;Integrated Security=True;")) 
    using (var cmd = conn.CreateCommand()) 
    { 
     conn.Open(); 
     cmd.CommandText = @"INSERT INTO docs (documentTitle, documentBody) 
          VALUES (@title,@body);"; 
     cmd.Parameters.AddWithValue("@title", txtTitle.Text.Trim()); 
     cmd.Parameters.AddWithValue("@body", txtBody.Text.Trim()); 

     cmd.ExecuteNonQuery();   
    } 
} 
1

最も単純なOnClickハンドラ内でまっすぐADO.NETを使用することです - それはスパゲッティコードとUI操作の混在につながる:

<asp:Button runat="server" Text="Submit" id="sub" OnClick="SaveDetails" /> 

<asp:TextBox runat="server" id="txtBody" /> 
<asp:TextBox runat="server" id="txtTitle" /> 

あなたのコードビハインドでこのような何かを試してみてください(テキストボックスなどの設定と読み取り)とデータアクセスコード - ではなくが良いアプローチです。どこ

- ここ最も簡単なアプローチ行く: - ORMを使用して、単に「アップ新」(プログラミングの観点から物事を簡単にするかもしれません(再び現実の使用は推奨されません)もちろん

protected void submit_onclick(object sender, EventArgs e) 
{ 
    string sqlStmt = "INSERT INTO dbo.YourTable(documentTitle, documentBody) " + 
         "VALUES(@docTitle, @docBody)"; 

    string connectionString = WebConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString; 

    using(SqlConnection conn = new SqlConnection(connectionString)) 
    using(SqlCommand cmd = new SqlCommand(sqlStmt, conn)) 
    { 
     cmd.Parameters.Add("@docTitle", SqlDbType.VarChar, 100).Value = tbxTitle.Text.Trim(); 
     cmd.Parameters.Add("@docBody", SqlDbType.VarChar, 100).Value = tbxBody.Text.Trim(); 

     conn.Open(); 
     cmd.ExecuteNonQuery(); 
     conn.Close(); 
    } 
} 

は、 Document、その.Title.Bodyのプロパティを設定し、.Save()などを呼び出してください)が、これらのORMには一定の学習曲線もあります。

また、シンプルから中程度の複雑な作業を行う場合や、ASP.NET開発に取り掛かっている場合は、Microsoft WebMatrixをチェックしてみませんか?これには、典型的なタスクを扱うのを助ける多くのヘルパーと「ラッパー」が含まれています。特に、データベースです。

part 5 of the intro tutorial on database developmentを参照してください。

関連する問題