C# 从mvc表单将数据过帐到数据库
我正在尝试将联系人数据从MVC表单保存到sql数据库。我还将数据保存到XML文档中。XML文档是使用正确的数据正确创建的,但我没有将数据发送到数据库。任何帮助都将不胜感激 控制器处理联系人数据:C# 从mvc表单将数据过帐到数据库,c#,sql,asp.net-mvc,asp.net-mvc-4,C#,Sql,Asp.net Mvc,Asp.net Mvc 4,我正在尝试将联系人数据从MVC表单保存到sql数据库。我还将数据保存到XML文档中。XML文档是使用正确的数据正确创建的,但我没有将数据发送到数据库。任何帮助都将不胜感激 控制器处理联系人数据: using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.IO; using
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Mvc;
using TestProject.Models;
using System.Xml.Serialization;
using System.Configuration;
using System.Windows.Forms;
using Rabbit.Bootstrap;
namespace TestProject.Controllers
{
public class ContactsController : Controller
{
[HttpGet]
public ActionResult Index()
{
Contact contact = new Contact();
return View(contact);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(Contact c)
{
if (ModelState.IsValid)
{
string ContactFileName = Path.GetFileName(String.Format("{0} {1}.xml", c.LastName, c.FirstName));
ContactFileName = (@"C:\Users\kevin.schultz\TestDocuments\" + ContactFileName);
if (System.IO.File.Exists(ContactFileName))
{
MessageBox.Show("The file already exists. A number will be added to create a unique file name", "Important", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
int i = 0;
while (System.IO.File.Exists(ContactFileName))
{
ContactFileName = String.Format("{0} - {1}", ContactFileName, i.ToString());
i++;
}
}
XmlSerializer ser = new XmlSerializer(c.GetType());
StreamWriter myWriter = new StreamWriter(ContactFileName);
ser.Serialize(myWriter, c);
myWriter.Close();
return View("ContactSuccess");
}
return View("ContactError");
}
[HttpGet]
public ActionResult Save()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Save (Contact s)
{
if (ModelState.IsValid)
{
try
{
using (ContactDataEntities CustData = new ContactDataEntities())
{
CustData.dbContacts.Add(
new dbContact()
{
FirstName = s.FirstName,
LastName = s.LastName,
PhoneHome = s.PhoneHome,
PhoneCell = s.PhoneCell,
Email = s.Email,
Address = s.Address,
City = s.City,
State = s.State,
ZipCode = s.ZipCode,
});
CustData.SaveChanges();
return View("ContactSuccess");
}
}
catch (Exception ex)
{
return View("ContactError");
}
}
else
{
MessageBox.Show("You are missing data, please ensure all fields are correct.", "Important", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
}
return View();
}
}
}
数据库
CREATE TABLE [dbo].[Table] (
[Id] INT NOT NULL,
[FirstName] TEXT NOT NULL,
[LastName] TEXT NOT NULL,
[PhoneHome] TEXT NOT NULL,
[PhoneCell] TEXT NOT NULL,
[Email] TEXT NOT NULL,
[Address] TEXT NOT NULL,
[City] TEXT NOT NULL,
[State] TEXT NOT NULL,
[ZipCode] TEXT NOT NULL,
模型
看法
@model TestProject.Models.Contact
@{
ViewBag.Title=“联系人页面”;
Layout=“~/Views/Shared/_Layout.cshtml”;
}
公司联络表格
@使用(Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@LabelFor(model=>model.FirstName,“FirstName”,新的{style=“display:inline;”})
@Html.EditorFor(model=>model.FirstName,新的{placeholder=“First Name”})
@Html.ValidationMessageFor(model=>model.FirstName)
@LabelFor(model=>model.LastName,“LastName”,新的{style=“display:inline;”})
@EditorFor(model=>model.LastName)
@Html.ValidationMessageFor(model=>model.LastName)
@LabelFor(model=>model.PhoneHome,“家庭电话”,新的{style=“display:inline;”})
@EditorFor(model=>model.PhoneHome)
@Html.ValidationMessageFor(model=>model.PhoneHome)
@LabelFor(model=>model.PhoneCell,“手机”,新的{style=“display:inline;”})
@EditorFor(model=>model.PhoneCell)
@Html.ValidationMessageFor(model=>model.PhoneCell)
@LabelFor(model=>model.Email,“电子邮件地址”,新的{style=“display:inline;”})
@EditorFor(model=>model.Email)
@Html.ValidationMessageFor(model=>model.Email)
@LabelFor(model=>model.Address,“街道地址”,新的{style=“display:inline;”})
@EditorFor(model=>model.Address)
@Html.ValidationMessageFor(model=>model.Address)
@LabelFor(model=>model.City,“City”,新的{style=“display:inline;”})
@EditorFor(model=>model.City)
@Html.ValidationMessageFor(model=>model.City)
@LabelFor(model=>model.State,“State”,新的{style=“display:inline;”})
@EditorFor(model=>model.State)
@Html.ValidationMessageFor(model=>model.State)
@LabelFor(model=>model.ZipCode,“邮政编码”,新的{style=“display:inline;”})
@EditorFor(model=>model.ZipCode)
@Html.ValidationMessageFor(model=>model.ZipCode)
}
您从未实际调用过save to the database方法。以下是我的建议:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(Contact c)
{
if (!ModelState.IsValid)
{
//should use client side validation for this as well.
MessageBox.Show("You are missing data, please ensure all fields are correct.", "Important", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
return View();
}
SaveToXml(c);
return SaveToDatabase(c);
}
public void SaveToXml(Contact c)
{
string ContactFileName = Path.GetFileName(String.Format("{0} {1}.xml", c.LastName, c.FirstName));
ContactFileName = (@"C:\Users\kevin.schultz\TestDocuments\\" + ContactFileName);
if (System.IO.File.Exists(ContactFileName))
{
MessageBox.Show("The file already exists. A number will be added to create a unique file name", "Important", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
int i = 0;
while (System.IO.File.Exists(ContactFileName))
{
ContactFileName = String.Format("{0} - {1}", ContactFileName, i.ToString());
i++;
}
}
XmlSerializer ser = new XmlSerializer(c.GetType());
StreamWriter myWriter = new StreamWriter(ContactFileName);
ser.Serialize(myWriter, c);
myWriter.Close();
}
public ActionResult SaveToDatabase(Contact s)
{
try
{
using (ContactDataEntities CustData = new ContactDataEntities())
{
CustData.dbContacts.Add(
new dbContact()
{
FirstName = s.FirstName,
LastName = s.LastName,
PhoneHome = s.PhoneHome,
PhoneCell = s.PhoneCell,
Email = s.Email,
Address = s.Address,
City = s.City,
State = s.State,
ZipCode = s.ZipCode,
});
CustData.SaveChanges();
return View("ContactSuccess");
}
}
catch (Exception ex)
{
return View("ContactError");
}
}
为了清晰起见,我进行了一些重构。您从未从视图中调用过save方法,因此我假设您希望一次单击就保存这两个方法。\转义\标记的主要原因是Stackoverflow无法将\“识别为闭引号(\也是转义字符)您是否在调试器中运行了它?是否出现错误?您使用的是SQL Server还是本地文件?仅从代码转储很难诊断多层问题。我认为这是因为您正在将数据发布到索引操作,而该操作正在将数据保存到xml,而不是数据库。在发布到保存操作时,您是否无法将数据保存到数据库您正在执行保存操作?请提供更多详细信息。我在这里也没有看到任何明显的问题。但是,有几件事值得指出:1)您的文件写入不是线程安全的。即使您添加了一个数字,也可能会发生冲突。当然,这需要两个同名的人同时发布,这是不太可能的,但可能类似于双贴子的东西会导致错误。2)对于EF工作使用
using
是个坏主意。创建上下文作为实例变量或将其注入控制器。3)Html.BeginForm
输出一个
元素,因此您的视图中有两个。我使用了调试器和e应用程序在写入数据库之前,但在创建XML文件之后,没有错误地完成。至于发布到保存操作,我不知道如何判断是否进入保存操作。
@model TestProject.Models.Contact
@{
ViewBag.Title = "Contact Page";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h4>Company Contact Form</h4>
<br />
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<form class="form-primary">
<fieldset class="form-group">
<div class="form-label">
@Html.LabelFor(model => model.FirstName, "First Name", new { style = "display:inline;" })
</div>
<div class="form.field">
@Html.EditorFor(model => model.FirstName, new { placeholder = "First Name" })
@Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="form-label">
@Html.LabelFor(model => model.LastName, "Last Name", new { style = "display:inline;" })
</div>
<div class="form.field">
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="form-label">
@Html.LabelFor(model => model.PhoneHome, "Home Phone", new { style = "display:inline;" })
</div>
<div class="form.field">
@Html.EditorFor(model => model.PhoneHome)
@Html.ValidationMessageFor(model => model.PhoneHome)
</div>
<div class="form-label">
@Html.LabelFor(model => model.PhoneCell, "Cell Phone", new { style = "display:inline;" })
</div>
<div class="form.field">
@Html.EditorFor(model => model.PhoneCell)
@Html.ValidationMessageFor(model => model.PhoneCell)
</div>
<div class="form-label">
@Html.LabelFor(model => model.Email, "Email Address", new { style = "display:inline;" })
</div>
<div class="form.field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<div class="form-label">
@Html.LabelFor(model => model.Address, "Street Address", new { style = "display:inline;" })
</div>
<div class="form.field">
@Html.EditorFor(model => model.Address)
@Html.ValidationMessageFor(model => model.Address)
</div>
<div class="form-label">
@Html.LabelFor(model => model.City, "City", new { style = "display:inline;" })
</div>
<div class="form.field">
@Html.EditorFor(model => model.City)
@Html.ValidationMessageFor(model => model.City)
</div>
<div class="form-label">
@Html.LabelFor(model => model.State, "State", new { style = "display:inline;" })
</div>
<div class="form.field">
@Html.EditorFor(model => model.State)
@Html.ValidationMessageFor(model => model.State)
</div>
<div class="form-label">
@Html.LabelFor(model => model.ZipCode, "Zip Code", new { style = "display:inline;" })
</div>
<div class="form.field">
@Html.EditorFor(model => model.ZipCode)
@Html.ValidationMessageFor(model => model.ZipCode)
</div>
<br />
<div>
<input type="submit" class="btn-custom" value="Submit" />
<input type="reset" class="btn-custom" value="Clear" />
</div>
</fieldset>
</form>
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(Contact c)
{
if (!ModelState.IsValid)
{
//should use client side validation for this as well.
MessageBox.Show("You are missing data, please ensure all fields are correct.", "Important", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
return View();
}
SaveToXml(c);
return SaveToDatabase(c);
}
public void SaveToXml(Contact c)
{
string ContactFileName = Path.GetFileName(String.Format("{0} {1}.xml", c.LastName, c.FirstName));
ContactFileName = (@"C:\Users\kevin.schultz\TestDocuments\\" + ContactFileName);
if (System.IO.File.Exists(ContactFileName))
{
MessageBox.Show("The file already exists. A number will be added to create a unique file name", "Important", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
int i = 0;
while (System.IO.File.Exists(ContactFileName))
{
ContactFileName = String.Format("{0} - {1}", ContactFileName, i.ToString());
i++;
}
}
XmlSerializer ser = new XmlSerializer(c.GetType());
StreamWriter myWriter = new StreamWriter(ContactFileName);
ser.Serialize(myWriter, c);
myWriter.Close();
}
public ActionResult SaveToDatabase(Contact s)
{
try
{
using (ContactDataEntities CustData = new ContactDataEntities())
{
CustData.dbContacts.Add(
new dbContact()
{
FirstName = s.FirstName,
LastName = s.LastName,
PhoneHome = s.PhoneHome,
PhoneCell = s.PhoneCell,
Email = s.Email,
Address = s.Address,
City = s.City,
State = s.State,
ZipCode = s.ZipCode,
});
CustData.SaveChanges();
return View("ContactSuccess");
}
}
catch (Exception ex)
{
return View("ContactError");
}
}