从mvc表单发送数据到数据库

本文关键字:数据 数据库 mvc 表单 | 更新日期: 2023-09-27 18:18:05

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

控制器处理联系人数据:

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>
}

从mvc表单发送数据到数据库

您从未实际调用保存到数据库的方法。以下是我的建议:

[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不识别'"是一个闭引号('也是转义字符)