I wrote this code to take a message information from HTML fields, and then executes insert command. but InsertCommand didn’t execute. What’s the problem here ?
<form action="FormParameter.aspx" method="post">
<label >Title :</label>
<input id="txtTitle" type="text" /><br />
<label >Subject:</label>
<input id="txtSubject" type="text" /><br />
<label >Category: </label>
<input id="txtCategory" type="text" /><br />
<input id="btnAdd" type="submit" value="Add" />
</form>
<form id="form1" runat="server">
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MessagesConnectionString %>"
InsertCommand="INSERT INTO [Messages] ([Title], [Subject], [CategoryID]) VALUES (@Title, @Subject, @CategoryID)"
SelectCommand="SELECT * FROM [Messages]" >
<InsertParameters>
<asp:FormParameter Name="Title" FormField="txtTitle" DefaultValue="No Title" />
<asp:FormParameter Name="Subject" FormField="txtSubject" DefaultValue="No Subject" />
<asp:FormParameter Name="CategoryID" FormField="txtCategory" DefaultValue="No Category" />
</InsertParameters>
</asp:SqlDataSource>
</form>
</body>
</html>
and in the codeFile (FormParameter.aspx.cs)
void Page_Load()
{
if (Request.Form["btnAdd"] != null)
SqlDataSource1.Insert();
}
You have add a form that call the FormParameter.aspx. This can not work like that, manually.
So keep one form only and place there all the controls, and there the post back will work correctly.
and on code behind is better to use
There is a way to make your code work, by disable the validation for this page, but you make then your page vulnerable to attacks.
Now I see again your code and I am not so sure that InsertParametres can get the values of non server controls, I think that you also need to change them to ServerControls.