As most people, I have read a seen a lot of examples of getting data from a form (html) and being able to effeciently handle the posted data say within an ASHX (Generic Handler) page... and from there say update a database via a stored procedure.. maybe I am trying to automate things too much?? !!
Now rather than have lines of code getting each form value, and then assigning to the stored procedure, is there a simplified way of doing this??
I am using JQuery.. I see the serialize function.. but just need to know if the end to end solution even can be done this way, or if I do indeed have to manually retrieve the values, and assign them to an object/stored proc....
Any help much appreciated!
You start by writing your generic handler:
public class TestHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
using (var connection = new SqlConnection(ConnectionString))
using (var command = connection.CreateCommand())
{
connection.Open();
command.CommandText = "NameOfYourSP";
command.CommandType = CommandType.StoredProcedure;
foreach (string name in context.Request.Form.Keys)
{
command.Parameters.AddWithValue("@" + name, context.Request.Form[name]);
}
command.ExecuteNonQuery();
}
context.Response.ContentType = "text/plain";
context.Response.Write("success");
}
public bool IsReusable
{
get { return false; }
}
}
Which you may call like this:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript" src="jquery-1.4.1.js"></script>
<script type="text/javascript">
$(function() {
$('a').click(function() {
$.ajax({
url: '/testhandler.ashx',
data: $('form').serialize(),
type: 'POST',
success: function(data) {
alert(data);
}
});
});
});
</script>
</head>
<body>
<form action="/test.ashx" method="post">
<input type="text" name="param1" value="value1" /><br/>
<input type="text" name="param2" value="value2" /><br/>
<input type="text" name="param3" value="value3" /><br/>
</form>
<a href="#">Submit data</a>
</body>
</html>
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.