我希望用户输入显示的所有数据(数据库中的列),填写并提交。但我不能让我的代码工作,我在这里做错了什么?我得到的错误:使用HTML帮助程序在SQL Server数据库中创建记录MVC
System.Data.SqlClient.SqlException: Incorrect syntax near 'Contact'.
型号:
namespace Project.Models
{
public class Contact
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public int Phone { get; set; }
public int CompanyID { get; set; }
}
}
查看:
@model Project.Contact
<h2>Create Contact</h2>
<table>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Email</th>
<th>Phone</th>
</tr>
<tr>
<td>@Html.TextBoxFor(m => m.FirstName)</td>
<td>@Html.TextBoxFor(m => m.LastName)</td>
<td>@Html.TextBoxFor(m => m.Email)</td>
<td>@Html.TextBoxFor(m => m.Phone)</td>
</tr>
@Html.HiddenFor(m => m.Id)
@Html.HiddenFor(m => m.CompanyID)
</table>
<br />
@using (Html.BeginForm())
{
<input type="button" name="button" class="button1" value="Create" />
}
控制器:
using Project.Models;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.Mvc;
namespace Project.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Create(List<Contact> model)
{
string query = "INSERT INTO Contact";
using (var connection = new SqlConnection(@"Data Source=.\SQLExpress;Initial Catalog=Sublime;Integrated Security=True"))
{
using (var command = new SqlCommand(query, connection))
{
connection.Open();
using (var dr = command.ExecuteReader())
{
if (dr.HasRows)
{
while (dr.Read())
{
var contact = new Contact();
contact.Id = dr.GetInt32(dr.GetOrdinal("Id"));
contact.FirstName = dr.GetString(dr.GetOrdinal("FirstName"));
contact.LastName = dr.GetString(dr.GetOrdinal("LastName"));
contact.Email = dr.GetString(dr.GetOrdinal("Email"));
contact.Phone = dr.GetInt32(dr.GetOrdinal("Phone"));
contact.CompanyID = dr.GetInt32(dr.GetOrdinal("CompanyID"));
model.Add(contact);
}
}
}
}
}
return View(model);
}
}
}
我不是也知道我的文本框的连接是否正确对我的行动...
有很多你的代码错误。在SO上有任何商业发布之前,您需要点击一些教科书并学习一些基本的T-SQL和ASP.NET MVC。 – Jakotheshadows
了解[SQL Server插入语句](https://technet.microsoft.com/zh-cn/library/dd776381(v = sql.105).aspx)的工作原理。 – ekad
具体有什么问题? – Malphai