我试图在不使用实体框架的情况下使用SQL在MVC中实现CRUD操作。我在插入时做得很好,但是在进入更新时,查看详细信息并删除我很困惑如何执行,那么有人可以帮助我吗?
这是我创建的代码:
我的模特:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.ComponentModel.DataAnnotations;
namespace Test.Models
{
public class Customers
{
public int CustomerID { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
[Display(Name = "Address Line 1")]
public string AddressLine1 { get; set; }
[Required]
[Display(Name = "Address Line 2")]
public string AddressLine2 { get; set; }
[Required]
[Display(Name = "City")]
public string City { get; set; }
[Required]
[Display(Name = "Postcode")]
public string Postcode { get; set; }
[Required]
[Display(Name = "Phone No")]
public string Phone { get; set; }
string strConnection = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString.ToString();
public void insert(Customers customers)
{
using (SqlConnection con = new SqlConnection(strConnection))
{
string sql = "insert into Customers values('" + customers.FirstName + "','" + customers.LastName + "','" + customers.AddressLine1 + "','" + customers.AddressLine2 + "','" + customers.City + "','" + customers.Postcode + "','" + customers.Phone + "')";
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
cmd.ExecuteNonQuery();
}
}
}
}
我的控制器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Test.Models;
namespace Test.Controllers
{
public class CustomersController : Controller
{
// GET: Customers
public ActionResult AddCustomerForm()
{
return View();
}
[HttpPost]
public ActionResult AddCustomerForm(FormCollection formCollection)
{
Customers customers = new Customers();
customers.FirstName = formCollection["FirstName"];
customers.LastName = formCollection["LastName"];
customers.AddressLine1 = formCollection["AddressLine1"];
customers.AddressLine2 = formCollection["AddressLine2"];
customers.City = formCollection["City"];
customers.Postcode = formCollection["Postcode"];
customers.Phone = formCollection["Phone"];
customers.insert(customers);
return View("CustomerRegSuccess", customers);
}
}
}