MVC- Entity Framework, The State ID must be a number 问题

MVC- Entity Framework, The State ID must be a number problem

我有 1 个 SQL 数据库,其中 3 个 table 与外键相连,我将在下面放图表的架构和我的问题的屏幕截图。

我想做的是当我从下拉列表中选择国家和州时,我想将其保存在第三个 table - 而不是他们的名字。我想保存他们的 ID。

这是来自我的控制器、Viewmodel 和 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; }

    }

并创建视图:

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

/Home/GetStateList 是否按预期工作?

在下拉列表中 select 一个状态后,转到浏览器调试器(Chrome 中的 F12),执行 $("#StateId:selected")$("#State").val() 显示分别正确 TAG 和 stateId?

此外,"<option value=`" + row.StateId + "`>" 中值周围的 `(重音)是故意的吗?试试单引号 (')?