首页 > 解决方案 > MVC 问题与在第三个中实现的 2 个不同 SQL 表中的级联下拉列表

问题描述

我有疑问,如果有人可以帮助我,我将非常感激。

我在 SQL 中有 1 个数据库,其中包含 3 个表:国家、州和联系人。我通过实体框架将数据库连接到 mvc。Country 和 State 是 2 个下拉列表,它们像父子或级联一样连接。我的问题是我需要创建新的联系人(在创建视图中)我需要以某种方式连接这 2 个下拉列表,然后保存在联系人表中(而不是通过他们的 ID)并显示他们的名字。我将发布代码。请帮忙!!

家庭控制器

    using AkvizicijeApp_3_3.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AkvizicijeApp_3_3.Controllers
{
    public class HomeController : Controller
    {
        Akvizicije_drop_downEntities db = new Akvizicije_drop_downEntities();
        public ActionResult Index()
        {
            List<Country> CountryList = db.Countries.ToList();
            ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
            return View();
        }

        public JsonResult GetStateList(int CountryId)
        {
            db.Configuration.ProxyCreationEnabled = false;
            List<State> StateList = db.States.Where(x => x.CountryId == CountryId).ToList();
            return Json(StateList, JsonRequestBehavior.AllowGet);
        }



        public ActionResult Create()

        {
            List<Country> CountryList = db.Countries.ToList();
            ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
            return View();
        }



        [HttpPost]

        public ActionResult Create(Contact model)

        {

            if (!ModelState.IsValid)

            {

                return View(model);

            }


            db.Contacts.Add(model);

            db.SaveChanges();


            return RedirectToAction("Index");



        }
    }
}

CountryStateViewModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AkvizicijeApp_3_3.Models
{
    public class CountryStateViewModel
    {
        public int CountryId { get; set; }
        public int StateId { get; set; }
        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; }
        

        public virtual Country Country { get; set; }

        public virtual State State { get; set; }
    }
}

并创建视图


@model AkvizicijeApp_3_3.Models.CountryStateViewModel

<h2>Create</h2>
<br /><br />
<div class="container">
    <div class="form-group">


        @if (ViewBag.CountryList != null)
        {

            @Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "--Select Country--", new { @class = "form-control" })

        }

    </div>
    <div class="form-group">


        @Html.DropDownListFor(model => model.StateId, new SelectList(" "), "--Select State--", new { @class = "form-control" })





    </div>
</div>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>CountryStateViewModel</h4>
        <hr />
        @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.EditorFor(model => model.CountryId, new { htmlAttributes = 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.EditorFor(model => model.StateId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.StateId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ContactsId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ContactsId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ContactsId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @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 (create, row) {
                    $("#StateId").append("<option value=`" + row.StateId + "`>" + row.StateName + "</option>")
                });
            });
        })
    });
</script>

标签: asp.net-mvcentity-frameworkmodel-view-controller

解决方案


将 CountryStateViewModel 作为参数传递给 post 操作而不是 Contact 模型,以便操作可以使用国家、州和联系信息。

[HttpPost]
public ActionResult Create(CountryStateViewModel csvm)
{
   if (!ModelState.IsValid)
   {
      return View(csvm);
   }
   //Contact model mapped from the View Model
   Contact model = new Contact()
   { 
     CountryId = csvm.CountryId, 
     StateId = csvm.StateId, 
     Name = csvm.PersonName, 
     //rest of properties 
   }; 
   db.Contacts.Add(model);
   db.SaveChanges();
   return RedirectToAction("Index");
}

我正在整合我上面评论中的相关部分,作为答案,以获得更好的可见性。


推荐阅读