当我点击“创建”时,它将被保存在数据库中以及发送给有关MailId的电子邮件,但是我收到的错误就是无法连接到sqlserverdatabase。 谁能帮我!!!
在模型中:我添加了数据库
using System;
using System.Collections.Generic;
namespace EmployeeMVC.Models
{
public partial class TblEmployeeDetail
{
public int id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailId { get; set; }
public System.DateTime DOB { get; set; }
public string MobileNo { get; set; }
public string Gender { get; set; }
public string Country { get; set; }
public string State { get; set; }
public string Skills { get; set; }
public string Address { get; set; }
}
}
在控制器中:我添加了方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EmployeeMVC.Models;
using System.Data;
using System.Data.Entity;
using System.Text;
using System.Data.Entity.Validation;
using System.Web.UI.WebControls;
using EmployeeMVC.Infrastructure;
using System.Web.Security;
using System.Text.RegularExpressions;
namespace EmployeeMVC.Controllers
{
public class EmployeeController : Controller
{
public EmployeeMVCEntities1 db = new EmployeeMVCEntities1();
//ss
// GET: /Employee/
public ActionResult Index()
{
using (db = new EmployeeMVCEntities1())
{
return View(db.TblEmployeeDetails.ToList());
}
}
// GET: /Employee/Details/5
public ActionResult Details(int id)
{
using (db = new EmployeeMVCEntities1())
{
return View(db.TblEmployeeDetails.Find(id));
}
}
public ActionResult Create()
{
var Country = (from s in db.TblCountries
select new
{
s.CountryId,
s.CountryName
}).OrderBy(c => c.CountryName);
ViewBag.Country = new SelectList(Country, "CountryId", "CountryName");
IEnumerable<TblSkill> skillList = (from x in db.TblSkills select x).ToList();
ViewBag.skill = skillList.Select(c => new SelectListItem{
Text = c.Skills.ToString(),
Value = c.SkillsId.ToString()
});
return View();
}
public ActionResult Verify(string id)
{
if (string.IsNullOrEmpty(id) || (!Regex.IsMatch(id, @"[0-9a-f]{8}\-([0-9a-f]{4}\-){3}[0-9a-f]{12}")))
{
ViewBag.Msg = "Not Good!!!";
return View();
}
else
{
var user = Membership.GetUser(new Guid(id));
if (!user.IsApproved)
{
user.IsApproved = true;
Membership.UpdateUser(user);
FormsAuthentication.SetAuthCookie(user.UserName, false);
return RedirectToAction("Index", "Home");
}
else
{
FormsAuthentication.SignOut();
ViewBag.Msg = "Account Already Approved";
return RedirectToAction("LogOn");
}
}
}
//
// POST: /Employee/Create
[HttpPost]
public ActionResult Create(TblEmployeeDetail emp)
{
int CId = Convert.ToInt32(emp.Country);
var Cname = (from c in db.TblCountries
where c.CountryId == CId
select c.CountryName).Single();
int SId = Convert.ToInt32(emp.Skills);
var Sname = (from sn in db.TblSkills
where sn.SkillsId == SId
select sn.Skills).SingleOrDefault();
if (ModelState.IsValid)
{
try
{
emp.Country = Cname;
emp.Skills = Sname;
db.TblEmployeeDetails.Add(emp);
db.SaveChanges();
// Attempt to register the user
MembershipCreateStatus createStatus;
//Make sure the user is not approve at this point!!!
Membership.CreateUser(emp.FirstName, emp.LastName, emp.EmailId,
null, null, true, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
EmailManager.SendConfirmationEmail(emp.EmailId);
FormsAuthentication.SetAuthCookie(emp.FirstName,false /* createPersistentCookie */);
return RedirectToAction("create", "Account");
}
else
{
ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
}
return RedirectToAction("Index");
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
StringBuilder sb = new StringBuilder();
foreach (var failure in dbEx.EntityValidationErrors)
{
sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());
foreach (var error in failure.ValidationErrors)
{
sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
sb.AppendLine();
}
}
throw new DbEntityValidationException("Entity Validation Failed - errors follow:\n" + sb.ToString(), dbEx); //addthe original exception as the innerException
}
}
return View(emp);
}
public ActionResult Edit(int id)
{
using (db = new EmployeeMVCEntities1())
{
return View(db.TblEmployeeDetails.Find(id));
}
}
// POST: /Employee/Edit/5
[HttpPost]
public ActionResult Edit(int id, TblEmployeeDetail EmployeeDetails)
{
try
{
if (ModelState.IsValid)
{
db.Entry(EmployeeDetails).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(EmployeeDetails);
}
catch
{
return View();
}
}
public ActionResult Delete(int id)
{
using (db = new EmployeeMVCEntities1())
{
return View(db.TblEmployeeDetails.Find(id));
}
}
//
// POST: /Employee/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteEmployee(int id)
{
//db.Entry(EmployeeDetails).State = EntityState.Deleted;
TblEmployeeDetail tbl = db.TblEmployeeDetails.Find(id);
db.TblEmployeeDetails.Remove(tbl);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
在基础架构文件夹中,EmailManager为:用于电子邮件确认
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using EmployeeMVC.Models;
using System.Net.Mail;
using System.Text;
namespace EmployeeMVC.Infrastructure
{
public class EmailManager
{
private const string EmailFrom = "noreplay@gmail.com";
public static void SendConfirmationEmail(string FirstName)
{
StringBuilder MailBody = new StringBuilder();
var user = Membership.GetUser(FirstName.ToString());
var confirmationGuid = user.ProviderUserKey.ToString();
var verifyUrl = HttpContext.Current.Request.Url.GetLeftPart
(UriPartial.Authority) + "/Employee/Verify" + confirmationGuid;
using (var client = new SmtpClient())
{
using (var message = new MailMessage(EmailFrom, user.Email))
{
message.Subject = "Please Verify your Account";
MailBody.Append("<html><table cellpadding='0' cellspacing='0' width='100%' align='center'>" +
"<tr><td><p>Dear " + user.UserName + "</p><br>");
MailBody.Append("To verify your account, please click the following link:<span style='font-weight:bold;'><a href=\""
+ verifyUrl + "\" target=\"http://localhost:59874\">"
+ verifyUrl + "</a></span> to complete your registration.<br>");
message.IsBodyHtml = true;
client.EnableSsl = true;
client.Send(message);
};
};
}
}
}
在Web.config中:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
<add name="EmployeeMVCEntities" connectionString="metadata=res://*/Models.EmployeeModel.csdl|res://*/Models.EmployeeModel.ssdl|res://*/Models.EmployeeModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=192.168.1.200;Initial Catalog=EmployeeMVC;User ID=sa;Password=DBserver123;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
<add name="EmployeeMVCEntities1" connectionString="metadata=res://*/Models.EmployeeModel.csdl|res://*/Models.EmployeeModel.ssdl|res://*/Models.EmployeeModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=192.168.1.200;Initial Catalog=EmployeeMVC;User ID=sa;Password=DBserver123;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear />
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network host="smtp.gmail.com" port="587" userName="idsignbilling@Gmail.com" password="iDsign@123" />
</smtp>
</mailSettings>
</system.net>
</configuration>
在创建视图中:
@model EmployeeMVC.Models.TblEmployeeDetail
@{
ViewBag.Title = "Create";
}
<h2>
Create</h2>
<link href="../../Content/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@*<script src="../../Scripts/EditorHookup.js" type="text/javascript"></script>
<script src="../../Scripts/RangeDateValidator.js" type="text/javascript"></script>*@
<link href="../../Content/Calendar.css" rel="stylesheet" type="text/css" />
<script src="../Scripts/jquery.ui.core.js" type="text/javascript"></script>
<script src="../Scripts/jquery.ui.datepicker.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#DOB").datepicker({
changeMonth: true,
changeYear: true,
yearRange: "-20:+0"
});
});
</script>
@*<script>
$(function () {
).datepicker();
});
</script>*@
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>TblEmployeeDetail</legend>
<div class="editor-label">
@Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.EmailId)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.EmailId)
@Html.ValidationMessageFor(model => model.EmailId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.DOB)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.DOB)
@Html.ValidationMessageFor(model => model.DOB)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.MobileNo)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.MobileNo)
@Html.ValidationMessageFor(model => model.MobileNo)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Gender)
</div>
<div class="editor-field">
@Html.RadioButtonFor(model => model.Gender, "Male", true)Male
@Html.RadioButtonFor(model => model.Gender, "Female", true)Female
@Html.ValidationMessageFor(model => model.Gender)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Country)
</div>
<div class="editor-field">
@* @Html.EditorFor(Model=> Model.Country)*@ @* @Html.DropDownListFor(m => m.Country, new SelectList(new string[] {"Select","India", "USA", "UK", "Australia"}, "Country"))*@
@* @Html.DropDownListFor(model=>model.Country,)*@ @*@Html.DropDownListFor(model => model.Country, new SelectList(Model.Country,"Value", "Text"), "Select Contry") *@
@*@Html.ValidationMessageFor(model=>Model.Country)*@
@Html.DropDownList("Country", "--select country--")
@Html.ValidationMessageFor(model => model.Country)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.State)
</div>
<div class="editor-field">
@* @Html.DropDownListFor(m => m.State, new SelectList(new string[] { "Select", "AP", "UP", "London", "Aust" }, "Country"))*@
@* @Html.DropDownList("State","Select State")*@
@Html.EditorFor(Model => Model.State)
@Html.ValidationMessageFor(model => model.State)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Skills)
</div>
<div class="editor-field">
@{
IEnumerable<SelectListItem> skill = ViewBag.skill;
foreach (var item in skill)
{
@Html.CheckBox("Skills", false, new { value = item.Value });
@*<input type="checkbox" name="skillsId" value="@item.Text" /> *@
<label>@item.Text</label>
@Html.ValidationMessageFor(model => model.Skills)
}
}
</div>
@* @Html.CheckboxList("skillId",new { @checked="checked" } )*@ @* @Html.CheckBox("skill", Model.skill == 1 ? true : false)*@
@*@Html.CheckBox("skill", model == null ? false : (model.Ischecked == 1 ? true : false), new { @value = "true" })*@
@* @Html.EditorFor(Model => Model.Skills)
@Html.ValidationMessageFor(model => model.Skills)*@ @* @{
List<EmployeeMVC.Models.TblSkills> tag = ViewData["skills"] as List<EmployeeMVC.Models.TblSkills>;
foreach (var item in skill)
{
@Html.CheckBoxList("Skills", true, new { value = item.SkillsId});
<label>@item.Skills</label>
@Html.ValidationMessageFor(model => model.Skills)
}
}*@ @*<div class="editor-field">
<table style="border: none;">
<tr>
@{
List<EmployeeMVC.Models.TblSkill> Skills = ViewBag.skill;
for (int i = 0; i < Skills.Count; i++)
{
Response.Write("<td style='border: none;'>");
Response.Write(string.Format("<input type='checkbox' id='skill{0}' name='skill' value='{0}' {2}/><label for='skill{0}'>{1}</label><br/>",
Skills[i].SkillsId, " " + Skills[i].Skills + " ",
(EmployeeMVC.Infrastructure.HtmlHelpers.GetTblSkill())
));
Response.Write("</td>");
if ((i + 1) % 3 == 0)
{
Response.Write("</tr><tr>");
}
}
}
</tr>
</table>
@Html.ValidationMessageFor(model => model.Skills)
</div>*@
<div class="editor-label">
@Html.LabelFor(model => model.Address)
</div>
<div class="editor-field">
@Html.TextAreaFor(model => model.Address)
@Html.ValidationMessageFor(model => model.Address)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
答案 0 :(得分:1)
成员资格提供程序使用ApplicationServices
连接字符串。确保此连接字符串指向正确的数据库。
从您的web.config中,它与其他Entity Framework连接字符串不同:
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
<add name="EmployeeMVCEntities" connectionString="metadata=res://*/Models.EmployeeModel.csdl|res://*/Models.EmployeeModel.ssdl|res://*/Models.EmployeeModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=192.168.1.200;Initial Catalog=EmployeeMVC;User ID=sa;Password=DBserver123;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
答案 1 :(得分:0)
如果您在localhost上运行此操作(通常是开发计算机上的情况),则可能没有安装SMTP服务器。如果是这种情况,您的电子邮件尝试将抛出异常。要解决这个问题,请转到此处获取Papercut:http://papercut.codeplex.com/ - 它将无缝拦截您的SMTP请求,以便您的代码可以继续执行其正在执行的操作。