gpt4 book ai didi

c# - 从 mvc 表单向数据库发布数据

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:02 24 4
gpt4 key购买 nike

我正在尝试将联系人数据从 MVC 表单保存到 sql 数据库。我还将数据保存到 XML 文档中。使用正确的数据正确创建了 XML 文档,但我没有将数据导入数据库。任何帮助将不胜感激。

Controller 处理联系人数据:

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,

模型

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;

namespace TestProject.Models
{

public class Contact
{
[Required]
[DisplayFormat(ConvertEmptyStringToNull = false)]
[StringLength(20, MinimumLength = 2, ErrorMessage = "Enter A Valid First Name")]
public string FirstName { get; set; }

[Required(ErrorMessage = "Enter A Valid Last Name")]
[DisplayFormat(ConvertEmptyStringToNull = false)]
[StringLength(20, MinimumLength = 2)]
public string LastName { get; set; }

[Required(ErrorMessage = "Enter A Valid Home Phone Number including area code")]
[DataType(DataType.PhoneNumber)]
public string PhoneHome { get; set; }

[Required(ErrorMessage = "Enter A Valid Cell Phone Number")]
[DataType(DataType.PhoneNumber)]
public string PhoneCell { get; set; }

[Required(ErrorMessage = "Enter A Valid Email Address")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }

[Required(ErrorMessage = "Enter A Valid Street Address")]
[DisplayFormat(ConvertEmptyStringToNull = false)]
[StringLength(120, MinimumLength = 4)]
public string Address { get; set; }

[Required(ErrorMessage = "Enter A Valid City Name")]
[DisplayFormat(ConvertEmptyStringToNull = false)]
[StringLength(30, MinimumLength = 2)]
public string City { get; set; }

[Required(ErrorMessage = "Enter A Valid State Abbreviation")]
[DisplayFormat(ConvertEmptyStringToNull = false)]
[StringLength(20, MinimumLength = 2)]
public string State { get; set; }

[Required(ErrorMessage = "Enter A Valid 5 Digit Zip Code")]
[DataType(DataType.PostalCode)]
public string ZipCode { get; set; }
}


}

查看

@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");
}
}

为了清晰起见,我重构了一点。您从未从您的 View 中调用过保存方法,因此我假设您希望一次单击即可保存两者。\正在转义\标签,主要是因为 Stackoverflow 无法将\"识别为闭引号(\也是转义字符)

关于c# - 从 mvc 表单向数据库发布数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25328252/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com