I have 1 SQL database with 3 tables connected with foreign key, I will put schema of diagram bellow and screenshot of my problem.
What I want to do is WHEN I choose Country and State from dropdownList I want to SAVE IT in third table - NOT BY THEIR name. I want to SAVE THEIR ID.
Here is the code from my Controller, Viewmodel, and View:
public ActionResult Create()
{
List<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CountryStateContactViewModel csvm)
{
if (!ModelState.IsValid)
{
return View(csvm);
}
Contact model = new Contact() { CountryId = csvm.CountryId, StateId = csvm.StateId, ContactId = csvm.ContactsId, ImeOsobe = csvm.PersonName, PrezimeOsobe = csvm.PersonLastName, Komentar = csvm.Comment, Email = csvm.Email, Aktivan = csvm.Active, kcbr = csvm.kcbr, KucniBroj = csvm.HouseNumber, NazivUlice = csvm.StreetName, NazivNaselja = csvm.SettlementName, PostanskiBroj = csvm.PostalCode, KontaktBroj = csvm.ContactNumber };
db.Contacts.Add(model);
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException db)
{
Exception raise = db;
foreach (var validationErrors in db.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
return RedirectToAction("Index");
}
public class CountryStateContactViewModel
{
public int CountryId { get; set; }
[Required]
public int StateId { get; set; }
public string StateName { get; set; }
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ContactsId { get; set; }
public int PostalCode { get; set; }
public string SettlementName { get; set; }
public string StreetName { get; set; }
public string HouseNumber { get; set; }
public string kcbr { get; set; }
public bool Active { get; set; }
public string PersonName { get; set; }
public string PersonLastName { get; set; }
public string ContactNumber { get; set; }
public string Email { get; set; }
public string Comment { get; set; }
}
And Create View:
@model AkvizicijeApp_3_9.Models.CountryStateContactViewModel
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>CountryStateContactViewModel</h4>
<hr />
<div class="form-group">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.CountryId, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "--Select Country--", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CountryId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.StateId, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.StateId, new SelectList(" "), "--Select State--", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.StateId, "", new { @class = "text-danger" })
</div>
</div>
@Html.LabelFor(model => model.PostalCode, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.PostalCode, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.PostalCode, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.SettlementName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.SettlementName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.SettlementName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.StreetName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.StreetName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.StreetName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.HouseNumber, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.HouseNumber, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.HouseNumber, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.kcbr, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.kcbr, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.kcbr, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Active, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model.Active)
@Html.ValidationMessageFor(model => model.Active, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.PersonName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.PersonName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.PersonName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.PersonLastName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.PersonLastName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.PersonLastName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ContactNumber, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ContactNumber, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ContactNumber, "", new { @class = "text-danger" })
</div>
</div>
<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.Comment, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Comment, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Comment, "", new { @class = "text-danger" })
</div>
</div>
<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")
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
$.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
$("#StateId").empty();
$.each(data, function (index, row) {
$("#StateId").append("<option value=`" row.StateId "`>" row.StateName "</option>")
});
});
})
});
</script>
CodePudding user response:
Is /Home/GetStateList is working as expected?
After you select a state in the drop-down, go to the browser debugger (F12 in Chrome), do $("#StateId:selected")
and $("#State").val()
show you the correct TAG and stateId respectively?
Also, in "<option value=`" row.StateId "`>"
is the `
(grave accent) around the value intentional? Try single quote (')?