带有 ajax 生成选项的下拉列表未保存 CityId 属性

我已经尝试了三天,但我无法找出错误,因为代码是正确的,但它的实现不是我想要的。 我正在使用三个表“州”、“城市”和“捐赠者”,我希望捐赠者在选择州时选择其州和城市,它显示指定的城市,但在保存其信息时,城市 ID 不会保存为图像中的那样在最后。

我首先使用 ap.net mvc 5 代码。

任何人都可以帮助并告诉我如何解决这个问题 以下是我的模型、控制器和视图:

@model WebApplication6.Models.Donator


@{

    Layout = "~/Views/Shared/_Layout.cshtml";

}


<!DOCTYPE html>


<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Create</title>

</head>

<body>

    @Scripts.Render("~/bundles/jquery")

    @Scripts.Render("~/bundles/jqueryval")


    <script type="text/jscript">

    $(function () {

        $('#State').change(function () {

            $.getJSON('/Donators/Citylist/' + $('#State').val(), function (data) {

                var items = '<option>Select a City</option>';

                $.each(data, function (i, city) {

                    items += "<option value='" + city.Value + "'>" + city.Text + "</option>";

                });

                $('#city').html(items);

            });

        });

    });

    </script>


    @using (Html.BeginForm()) 

    {

        @Html.AntiForgeryToken()


        <div class="form-horizontal">

            <h4>Donator</h4>

            <hr />

            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            <div class="form-group">

                @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

                <div class="col-md-10">

                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })

                    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

                </div>

            </div>


慕容森
浏览 51回答 1
1回答

holdtom

在您的 POST 创建控制器操作中,您没有绑定 CityId。您正在绑定 CountryId,这是一个拼写错误吗?[HttpPost][ValidateAntiForgeryToken]public ActionResult Create([Bind(Include = "Id,Name,gender,Age,BloodType,CountryId,StateId,CityId")] Donator donator){&nbsp; &nbsp;// add cityId to the bind parameters above&nbsp; &nbsp;...}您需要将 html 帮助程序上的 City 更新为 CityId。// please update first string parameter to CityId@Html.DropDownList("CityId", new SelectList(string.Empty, "Value", "Text"), htmlAttributes: new { id = "city", @class = "form-control" })
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5