我正在编写一个Web应用程序,用户可以在其中注册并登录到网站。
我有一个带有一系列文本框和提交按钮的ASP.NET Web表单。当我在PHP中执行相同的操作时,按下提交按钮时,会创建一个User类,并将文本框的内容传递给addUser()函数,该函数接受这些参数并将它们插入到数据库中,现在我我想在C#中做同样的事情。
理想情况下,我想使用MVC类型的设计。控制器(文本框和按钮)应该收集文本框中的信息,并将其传递给模型(User类),该模型应该连接到数据库并执行必要的insert语句。如何使类连接到数据库?它需要什么参数?
我是否需要在传递给User类构造函数的页面上使用SqlDataSource对象?还是别的什么?
答案 0 :(得分:3)
您的控制器应如下所示:
[HttpPost]
[ActionName("MyAction")]
public ActionResult MyAction(MyModel model) {
// ... model has been loaded with data from the form, now work with it.
// ex: MyDataLayer.Save(model);
}
将您的视图表单设置为POST到“MyAction”,您的模型将通过model binding创建并预加载。
答案 1 :(得分:1)
好吧,在您的Razor .cshtml
视图中,您应该有一个用于注册用户的模型。
这是Razor Views的观点。帮助将数据绑定到HTML。
看起来像......
@model YourProject.Models.UserRegister
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>User Registration</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
</div>
</div>
这将是您User
课程的副本。
当用户点击表单上的提交按钮时,它需要Controller中的一个方法来处理{J} M所指的POST
。由于您使用上面的模型属性绑定到HTML元素,因此用户正在填写User
模型的属性,我们将在控制器中捕获它。
我不会在Controller中进行任何数据库登录,但为了简单起见,它取决于您与数据库(实体框架,企业库等)的交互方式。
您可以从此处调用dbContext
并使用Linq
提交更改,也可以编写内联SQL将这些更改写入数据库,或调用存储过程。然后,您必须将User类的这些属性映射到SQL参数。
所以,整个流程:
用户填写模型 - &gt; POST到控制器 - &gt;将属性映射到SQL参数或使用DbContext
实体框架提交更改。
答案 2 :(得分:1)
这是我创建的sample project的简短摘录。
您需要定义模型对象。而不是用户(因为处理密码是一个小问题),这个例子将用于商店中的产品。
public class Product
{
public int Id {get; set;}
public string Name {get; set;}
public string Description {get; set;}
public double Price {get; set;}
}
您需要为数据层定义接口。
public interface IStoreRepository
{
Product GetProductById(int id);
List<Product> GetAllProducts();
void AddNewProduct(Product product);
void UpdateProduct(Product product);
void DeleteProduct(int id);
}
然后你编写一个具体的类来实现数据层接口并执行实际的CRUD(Create Read Update Delete)。这是MS SQL Server实现的样子。
public class MsSqlStoreRepository : IStoreRepository
{
private string ConnectionString { get; set; }
public MsSqlStoreRepository(string connectionString)
{
ConnectionString = connectionString;
}
private Product GenerateProductFromDataRow(DataRow row)
{
return new Product()
{
Id = row.Field<int>("id"),
Name = row.Field<string>("name"),
Description = row.Field<string>("description"),
Price = row.Field<double>("price")
};
}
public Product GetProductById(int id)
{
var command = new SqlCommand("select id, name, description, price from products where id=@id");
command.Parameters.AddWithValue("id", id);
var dt = MsSqlDatabaseHelpers.GetDataTable(command, ConnectionString);
return dt.AsEnumerable().Select(r => GenerateProductFromDataRow(r)).Single();
}
public List<Product> GetAllProducts()
{
var command = new SqlCommand("select id, name, description, price from products");
var dt = MsSqlDatabaseHelpers.GetDataTable(command, ConnectionString);
return dt.AsEnumerable().Select(r => GenerateProductFromDataRow(r)).ToList();
}
public void AddNewProduct(Product product)
{
var command = new SqlCommand("insert into products (id, name, description, price) values (@id, @name, @description, @price)");
command.Parameters.AddWithValue("id", product.Id);
command.Parameters.AddWithValue("name", product.Name);
command.Parameters.AddWithValue("description", product.Description);
command.Parameters.AddWithValue("price", product.Price);
MsSqlDatabaseHelpers.ExecuteNonQuery(command, ConnectionString);
}
public void UpdateProduct(Product product)
{
var command = new SqlCommand("update products set name=@name, description=@description, price=@price where id=@id");
command.Parameters.AddWithValue("id", product.Id);
command.Parameters.AddWithValue("name", product.Name);
command.Parameters.AddWithValue("description", product.Description);
command.Parameters.AddWithValue("price", product.Price);
MsSqlDatabaseHelpers.ExecuteNonQuery(command, ConnectionString);
}
public void DeleteProduct(int id)
{
var command = new SqlCommand("delete from products where id=:id");
command.Parameters.AddWithValue("id", id);
MsSqlDatabaseHelpers.ExecuteNonQuery(command, ConnectionString);
}
}
现在我们已经关注了问题,而唯一剩下的就是编写实际的UI逻辑。假设您正在使用Web表单,它可能如下所示:
[Inject] //using Ninject to inject MsSqlStoreRepository
public IStoreRepository Repo { get; set; }
protected void AddProductBtn_Click(object sender, EventArgs e)
{
Product product = new Product()
{
Id = Int32.Parse(IdTB.Text),
Name = NameTB.Text,
Description = DescriptionTB.Text,
Price = Double.Parse(PriceTB.Text)
};
Repo.AddNewProduct(product);
//now clear the form or show success message etc
}
请注意,我的网页不知道关于MsSqlStoreRepository
,因为它仅通过IStoreRepository
进行通信。这样做可以确保我不会在我的网页中执行任何与数据库相关的内容,并且我可以通过创建一个继承自IStoreRepository
的新具体类来随意交换数据库。如果你看一下我答案顶部的链接,你会发现我已经做到了。