I have a cascading dropdown list which will not allow me to do a create view.
The controller is as follows:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using IdentitySample.Models;
using MvcNOK.Models;
using System.Threading.Tasks;
namespace MvcNOK.Controllers
{
public class IndividualsController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
public ActionResult Index(string individualFirst, string searchString)
{
var FirstList = new List<string>();
var FirstQry = from d in db.Individuals.Include(i => i.Cities).Include(i => i.Countries).Include(i => i.Eras).Include(i => i.Genders).Include(i => i.Sources).Include(i => i.States)
orderby d.First
select d.First;
FirstList.AddRange(FirstQry.Distinct());
ViewBag.individualFirst = new SelectList(FirstList);
var individuals = from m in db.Individuals
select m;
if (!String.IsNullOrEmpty(searchString))
{
individuals = individuals.Where(s => s.Last.Contains(searchString));
}
if (!string.IsNullOrEmpty(individualFirst))
{
individuals = individuals.Where(x => x.First == individualFirst);
}
return View(individuals.ToList());
}
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Individual individual = db.Individuals.Find(id);
if (individual == null)
{
return HttpNotFound();
}
return View(individual);
}
public ActionResult Create()
{
ViewBag.CitieId = new SelectList(db.Cities, "CitieId", "Name");
ViewBag.CountrieId = new SelectList(db.Countries, "CountrieId", "Name");
ViewBag.EraId = new SelectList(db.Eras, "EraId", "Name");
ViewBag.GenderId = new SelectList(db.Genders, "GenderId", "Name");
ViewBag.SourceId = new SelectList(db.Sources, "SourceId", "Title");
ViewBag.StateId = new SelectList(db.States, "StateId", "Name");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "IndividualId,Email,Last,First,Middle,GenderId,Occupation,DOB,EraId,CountrieId,StateId,CitieId,Note,InternalImage,ItemPictureUrl,SourceId,DeathId")] Individual individual)
{
if (ModelState.IsValid)
{
db.Individuals.Add(individual);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CitieId = new SelectList(db.Cities, "CitieId", "Name", individual.CitieId);
ViewBag.CountrieId = new SelectList(db.Countries, "CountrieId", "Name", individual.CountrieId);
ViewBag.EraId = new SelectList(db.Eras, "EraId", "Name", individual.EraId);
ViewBag.GenderId = new SelectList(db.Genders, "GenderId", "Name", individual.GenderId);
ViewBag.SourceId = new SelectList(db.Sources, "SourceId", "Title", individual.SourceId);
ViewBag.StateId = new SelectList(db.States, "StateId", "Name", individual.StateId);
return View(individual);
}
public JsonResult StateList(int Id)
{
var state = from s in db.States
where s.CountrieId == Id
select s;
return Json(new SelectList(state.ToArray(), "StateId", "Name"), JsonRequestBehavior.AllowGet);
}
public JsonResult Citielist(int id)
{
var citie = from c in db.Cities
where c.StateId == id
select c;
return Json(new SelectList(citie.ToArray(), "CitieId", "Name"), JsonRequestBehavior.AllowGet);
}
public IList<State> Getstate(int CountrieId)
{
return db.States.Where(m => m.CountrieId == CountrieId).ToList();
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadClassesByCountrieId(string Name)
{
var stateList = this.Getstate(Convert.ToInt32(Name));
var stateData = stateList.Select(m => new SelectListItem()
{
Text = m.Name,
Value = m.CountrieId.ToString(),
});
return Json(stateData, JsonRequestBehavior.AllowGet);
}
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Individual individual = db.Individuals.Find(id);
if (individual == null)
{
return HttpNotFound();
}
ViewBag.CitieId = new SelectList(db.Cities, "CitieId", "Name", individual.CitieId);
ViewBag.CountrieId = new SelectList(db.Countries, "CountrieId", "Name", individual.CountrieId);
ViewBag.EraId = new SelectList(db.Eras, "EraId", "Name", individual.EraId);
ViewBag.GenderId = new SelectList(db.Genders, "GenderId", "Name", individual.GenderId);
ViewBag.SourceId = new SelectList(db.Sources, "SourceId", "Title", individual.SourceId);
ViewBag.StateId = new SelectList(db.States, "StateId", "Name", individual.StateId);
return View(individual);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "IndividualId,Email,Last,First,Middle,GenderId,Occupation,DOB,EraId,CountrieId,StateId,CitieId,Note,InternalImage,ItemPictureUrl,SourceId,DeathId")] Individual individual)
{
if (ModelState.IsValid)
{
db.Entry(individual).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CitieId = new SelectList(db.Cities, "CitieId", "Name", individual.CitieId);
ViewBag.CountrieId = new SelectList(db.Countries, "CountrieId", "Name", individual.CountrieId);
ViewBag.EraId = new SelectList(db.Eras, "EraId", "Name", individual.EraId);
ViewBag.GenderId = new SelectList(db.Genders, "GenderId", "Name", individual.GenderId);
ViewBag.SourceId = new SelectList(db.Sources, "SourceId", "Title", individual.SourceId);
ViewBag.StateId = new SelectList(db.States, "StateId", "Name", individual.StateId);
return View(individual);
}
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Individual individual = db.Individuals.Find(id);
if (individual == null)
{
return HttpNotFound();
}
return View(individual);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Individual individual = db.Individuals.Find(id);
db.Individuals.Remove(individual);
db.SaveChanges();
return RedirectToAction("Index");
}
public async Task<ActionResult> RenderImage(int id)
{
Individual individual = await db.Individuals.FindAsync(id);
byte[] photoBack = individual.InternalImage;
return File(photoBack, "image/png");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
The create view is as follows:
@model MvcNOK.Models.Individual
@using MvcNOK.Extensions
@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@Scripts.Render("~/bundles/jquery")
<script type="text/jscript">
$(function () {
$('#Countrie').change(function () {
$.getJSON('/Individuals/StateList/' + $('#Countrie').val(), function (data) {
var items = '<option>Select a State</option>';
$.each(data, function (i, state) {
items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
});
$('#State').html(items);
});
});
$('#State').change(function () {
$.getJSON('/Individuals/Citielist/' + $('#State').val(), function (data) {
var items = '<option>Select a City</option>';
$.each(data, function (i, citie) {
items += "<option value='" + citie.Value + "'>" + citie.Text + "</option>";
});
$('#citie').html(items);
});
});
});
</script>
<h2>Create</h2>
@using (Html.BeginForm("Create", "Individuals", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Individual</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Last, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Last, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Last, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.First, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.First, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.First, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Middle, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Middle, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Middle, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.GenderId, "GenderId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("GenderId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.GenderId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Occupation, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Occupation, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Occupation, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.DOB, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.DOB, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.DOB, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.EraId, "EraId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("EraId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.EraId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CountrieId, "CountrieId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Countrie", ViewBag.CountrieId as SelectList, "Select a Country", new { id = "Countrie" })<br />
@Html.ValidationMessageFor(model => model.CountrieId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.StateId, "StateId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<select id="State" name="state"></select>
@Html.ValidationMessageFor(model => model.StateId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CitieId, "CitieId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<select id="citie" name="citie"></select>
@Html.ValidationMessageFor(model => model.CitieId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Note, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Note, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Note, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ItemPictureUrl, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ItemPictureUrl, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ItemPictureUrl, "", new { @class = "text-danger" })
</div>
</div>
<div class="editor-label">
Upload Image
</div>
<div class="editor-field">
@Html.FileFor(model => model.File)
@Html.ValidationMessageFor(model => model.File)
</div>
<br />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
I get the following error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Individuals_dbo.Cities_CitieId". The conflict occurred in database "C:\GENEALOGY1.3\MVCNOK\MVCNOK\APP_DATA\MVCNOKDB.MDF", table "dbo.Cities", column 'CitieId'.
The statement has been terminated. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Individuals_dbo.Cities_CitieId". The conflict occurred in database "C:\GENEALOGY1.3\MVCNOK\MVCNOK\APP_DATA\MVCNOKDB.MDF", table "dbo.Cities", column 'CitieId'.
The statement has been terminated.
Source Error:
Line 82: {
Line 83: db.Individuals.Add(individual);
Line 84: db.SaveChanges();
Line 85: return RedirectToAction("Index");
Line 86: }
Source File: C:\Genealogy1.3\MvcNOK\MvcNOK\Controllers\IndividualsController.cs Line: 84
Stack Trace:
[SqlException (0x80131904): The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Individuals_dbo.Cities_CitieId". The conflict occurred in database "C:\GENEALOGY1.3\MVCNOK\MVCNOK\APP_DATA\MVCNOKDB.MDF", table "dbo.Cities", column 'CitieId'.
The statement has been terminated.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +2442126
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5736904
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +628
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +3731
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +58
System.Data.SqlClient.SqlDataReader.get_MetaData() +89
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +379
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest) +2026
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +375
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +53
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +240
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c) +14
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +72
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext) +402
System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior) +166
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues) +234
System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() +159
[UpdateException: An error occurred while updating the entries. See the inner exception for details.]
System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() +329
System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut) +11
System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update(T noChangesResult, Func`2 updateFunction) +132
System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update() +106
System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35() +13
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +288
System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction) +157
System.Data.Entity.Core.Objects.<>c__DisplayClass2a.<SaveChangesInternal>b__27() +25
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +162
System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction) +221
System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options) +11
System.Data.Entity.Internal.InternalContext.SaveChanges() +113
[DbUpdateException: An error occurred while updating the entries. See the inner exception for details.]
System.Data.Entity.Internal.InternalContext.SaveChanges() +191
System.Data.Entity.Internal.LazyInternalContext.SaveChanges() +27
System.Data.Entity.DbContext.SaveChanges() +22
MvcNOK.Controllers.IndividualsController.Create(Individual individual) in C:\Genealogy1.3\MvcNOK\MvcNOK\Controllers\IndividualsController.cs:84
lambda_method(Closure , ControllerBase , Object[] ) +103
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +225
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9744373
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1073.0
Can anyone help?
What I have tried:
I have tried designating a foreign key label to the citie, countrie, and state model, and nothing worked..