如何创建将信息提交到数据库的单页ASP.NET应用程序?

时间:2022-01-14 04:09:55

Ok, I know this is embarassing since I've been working as a web developer with ASP.NET for months, but I used to starting with a largely prepackaged ASP.NET MVC site with routing, controllers, etc., and extending it from there. All I need to do right now is creating a single-page ASP.NET page that submits a form to the database.

好吧,我知道这很令人尴尬,因为我几个月来一直在使用ASP.NET作为Web开发人员,但我过去常常使用路由,控制器等在很大程度上预先打包的ASP.NET MVC站点,并从那里。我现在需要做的就是创建一个单页的ASP.NET页面,将表单提交给数据库。

I already have my table in the database

我已经在数据库中有我的表了

 CREATE TABLE stuff ( field1 VARCHAR (100), field2 VARCHAR (100) ); 

and I have a form in my HTML

我的HTML中有一个表单

<form id="myform">
    <input type="text" name="field1"/>
    <input type="text" name="field2"/>
    <input type="submit"/>
</form>

and I have a function

我有一个功能

  $('#myform input[type="submit"]').click(function(){
       var that = this;
       $.ajax({
           url: '????',
           method: 'POST', 
           data: new FormData($(that).closest('form')[0]),
           success: function() { alert("Well, at least this succeeded"); }
       });

I started in Visual Studio with a "ASP.NET Empty Web Application Visual C#" but I seriously don't know what type of file I need to right-click-Add to the project to handle this. All I'm trying to do is a simple insertion of the inputs field1 and field2 into their corresponding columns in the database. I can't find any resources of how to build an ASP.NET page from scratch and all the books I've ever read start with a template that has everything hooked up, so ...

我在Visual Studio中使用“ASP.NET空Web应用程序Visual C#”开始,但我真的不知道我需要右键单击什么类型的文件 - 添加到项目来处理这个问题。我想要做的就是将输入field1和field2简单地插入到数据库中相应的列中。我找不到任何关于如何从头开始构建ASP.NET页面的资源,我读过的所有书籍都以一个连接了所有内容的模板开头,所以...

Can someone give me a hint of how to connect the dots here?

有人能给我一些如何在这里连接点的提示吗?

3 个解决方案

#1


1  

Here is the Code

这是守则

web method must be public and static

web方法必须是公共的和静态的

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">  
    <title></title>  
     <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>  
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>  
    <link rel="Stylesheet" href="StyleSheet.css" />  

    <script type="text/javascript">
        $(document).ready(function () {
            $('#Button1').click(function (e) {
                alert('Data Saved')
                var commentsCorrespondence;

                var ddlST = $('#ddlStatus option:selected').val();// get dropdown selected value in ddlST variable
                var chkbox = $('#ChkValue').val();// get checkbox value in chkbox
                var Date = $('#txtDate').val();//get textbox value in date variable
                $.ajax({
                    type: "POST",
                    url: "AutoCompleteCity.aspx/SaveData", //this is the url from which you call your web method ! in my case its /Default.aspx and method name is SaveData
                    data: "{'status': '" + ddlST + "','chkBoxValue': '" + chkbox + "','DueDate': '" + Date + "'}",// These are the method parameters in my case 'status' , 'chkBoxValue' and 'DueDate' are parameters
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: alert('Data Saved'),
                    failure: function (response) {
                        Message = response.d;
                    }
                });

                return false;
            });
        });
    </script>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
        <asp:DropDownList ID="ddlStatus" runat="server"></asp:DropDownList>
        <asp:CheckBox ID="ChkValue" runat="server" />
        <asp:Button ID="Button1" runat="server" Text="Button" />
        <br />  
        <br />  
        <br />  
    </div>  
    </form>  

</body>  
</html>  

Code Behind

代码背后

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class AutoCompleteCity : System.Web.UI.Page
{
    [WebMethod]
    public static void SaveData(string status, string chkBoxValue, string DueDate)
    {
        List<string> Emp = new List<string>();
        string query = string.Format("Insert Into [Table] Values ({0},{1},{2})", status, chkBoxValue, DueDate);
        using (SqlConnection con = new SqlConnection("your Connection string"))
        {
            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                con.Open();
                cmd.ExecuteNonQuery();
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

#2


2  

Create a WebMethod in cs file of the same page

在同一页面的cs文件中创建WebMethod

[WebMethod]
Public static bool FxName(string field1, string field2){
// Do the code here for saving
}


in ajax
$('#myform input[type="submit"]').click(function(){
       var that = this;
       $.ajax({
           url: 'pagename.aspx/FxName',
           method: 'POST',
           contentType: 'application/json; charset=utf-8',
           dataType: 'json',
           data: {"field1": valueoftextbox,"field2":valueoftextbox},
           success: function() { alert("Well, at least this succeeded"); }
       });

#3


1  

Given the template you're using, I think a controller from ASP.NET Web API will be more appropriate than WebMethods (which were introduced in .NET 3.5 and haven't changed since...).

鉴于您正在使用的模板,我认为ASP.NET Web API中的控制器将比WebMethods更适合(WebMethods是在.NET 3.5中引入的,并且自从......以来没有改变)。

Add an ApiController to your project:

将ApiController添加到项目中:

public class FooController : ApiController
{
    [HttpPost]
    public IHttpActionResult PostForm(FormInput input)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        // You'll have to create the repository class as well as inject it
        // into your controller. If you don't know what I'm talking about,
        // google "dependency injection asp.net webapi" for more info.
        _repository.SaveFormDataToDb(input.Field1, input.Field2);
        return Ok();
    }
}

You'll also need to create the input model:

您还需要创建输入模型:

[DataContract]
public class FormInput
{
    [DataMember]
    [Required]
    public string Field1 { get; set; }

    [DataMember]
    [Required]
    public string Field1 { get; set; }
}

The [DataContract] and [DataMember] attributes are from System.Runtime.Serialization. [Required] is from System.ComponentModel.DataAnnotations, and will work in conjunction with ModelState.IsValid() to validate input - you can add a bunch of other attributes too (or write your own!) to specify other rules than just required fields.

[DataContract]和[DataMember]属性来自System.Runtime.Serialization。 [必需]来自System.ComponentModel.DataAnnotations,并将与ModelState.IsValid()一起使用以验证输入 - 您也可以添加一堆其他属性(或编写您自己的!)以指定除了必需字段之外的其他规则。

Depending on how you're planning to host this (in IIS or not) the way you hook up the dependency injection, routing etc is a little different, but the tutorials on asp.net are legio.

根据你计划如何托管这个(在IIS中或不在IIS中)连接依赖注入的方式,路由等有点不同,但asp.net上的教程是legio。

Good luck! :)

祝你好运! :)

#1


1  

Here is the Code

这是守则

web method must be public and static

web方法必须是公共的和静态的

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">  
    <title></title>  
     <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>  
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>  
    <link rel="Stylesheet" href="StyleSheet.css" />  

    <script type="text/javascript">
        $(document).ready(function () {
            $('#Button1').click(function (e) {
                alert('Data Saved')
                var commentsCorrespondence;

                var ddlST = $('#ddlStatus option:selected').val();// get dropdown selected value in ddlST variable
                var chkbox = $('#ChkValue').val();// get checkbox value in chkbox
                var Date = $('#txtDate').val();//get textbox value in date variable
                $.ajax({
                    type: "POST",
                    url: "AutoCompleteCity.aspx/SaveData", //this is the url from which you call your web method ! in my case its /Default.aspx and method name is SaveData
                    data: "{'status': '" + ddlST + "','chkBoxValue': '" + chkbox + "','DueDate': '" + Date + "'}",// These are the method parameters in my case 'status' , 'chkBoxValue' and 'DueDate' are parameters
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: alert('Data Saved'),
                    failure: function (response) {
                        Message = response.d;
                    }
                });

                return false;
            });
        });
    </script>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
        <asp:DropDownList ID="ddlStatus" runat="server"></asp:DropDownList>
        <asp:CheckBox ID="ChkValue" runat="server" />
        <asp:Button ID="Button1" runat="server" Text="Button" />
        <br />  
        <br />  
        <br />  
    </div>  
    </form>  

</body>  
</html>  

Code Behind

代码背后

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class AutoCompleteCity : System.Web.UI.Page
{
    [WebMethod]
    public static void SaveData(string status, string chkBoxValue, string DueDate)
    {
        List<string> Emp = new List<string>();
        string query = string.Format("Insert Into [Table] Values ({0},{1},{2})", status, chkBoxValue, DueDate);
        using (SqlConnection con = new SqlConnection("your Connection string"))
        {
            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                con.Open();
                cmd.ExecuteNonQuery();
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

#2


2  

Create a WebMethod in cs file of the same page

在同一页面的cs文件中创建WebMethod

[WebMethod]
Public static bool FxName(string field1, string field2){
// Do the code here for saving
}


in ajax
$('#myform input[type="submit"]').click(function(){
       var that = this;
       $.ajax({
           url: 'pagename.aspx/FxName',
           method: 'POST',
           contentType: 'application/json; charset=utf-8',
           dataType: 'json',
           data: {"field1": valueoftextbox,"field2":valueoftextbox},
           success: function() { alert("Well, at least this succeeded"); }
       });

#3


1  

Given the template you're using, I think a controller from ASP.NET Web API will be more appropriate than WebMethods (which were introduced in .NET 3.5 and haven't changed since...).

鉴于您正在使用的模板,我认为ASP.NET Web API中的控制器将比WebMethods更适合(WebMethods是在.NET 3.5中引入的,并且自从......以来没有改变)。

Add an ApiController to your project:

将ApiController添加到项目中:

public class FooController : ApiController
{
    [HttpPost]
    public IHttpActionResult PostForm(FormInput input)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        // You'll have to create the repository class as well as inject it
        // into your controller. If you don't know what I'm talking about,
        // google "dependency injection asp.net webapi" for more info.
        _repository.SaveFormDataToDb(input.Field1, input.Field2);
        return Ok();
    }
}

You'll also need to create the input model:

您还需要创建输入模型:

[DataContract]
public class FormInput
{
    [DataMember]
    [Required]
    public string Field1 { get; set; }

    [DataMember]
    [Required]
    public string Field1 { get; set; }
}

The [DataContract] and [DataMember] attributes are from System.Runtime.Serialization. [Required] is from System.ComponentModel.DataAnnotations, and will work in conjunction with ModelState.IsValid() to validate input - you can add a bunch of other attributes too (or write your own!) to specify other rules than just required fields.

[DataContract]和[DataMember]属性来自System.Runtime.Serialization。 [必需]来自System.ComponentModel.DataAnnotations,并将与ModelState.IsValid()一起使用以验证输入 - 您也可以添加一堆其他属性(或编写您自己的!)以指定除了必需字段之外的其他规则。

Depending on how you're planning to host this (in IIS or not) the way you hook up the dependency injection, routing etc is a little different, but the tutorials on asp.net are legio.

根据你计划如何托管这个(在IIS中或不在IIS中)连接依赖注入的方式,路由等有点不同,但asp.net上的教程是legio。

Good luck! :)

祝你好运! :)