MVC级联下拉列表http帖子

时间:2016-12-29 18:19:55

标签: jquery asp.net asp.net-mvc

当我点击提交按钮时,我将丢失创建的级联下拉列表

控制器

    public ActionResult Create()
    {
        ViewBag.gradeLs = GetGradeLevels();          
        return View();
    }

    public SelectList GetGradeLevels()
    {
        var gradeLs = db.GradeLevels;
        return new SelectList(
            gradeLs.ToArray(),
            "GradeLevelId",
            "GradeLevel1"
            );
    }

    [HttpPost]
    public ActionResult GetTestsbyGradeLevelId(int gradeLevelId)
    {
        var listTests = GetAllTests(gradeLevelId);
        SelectList selectListOfTests = new SelectList(listTests, "TestId", "TestTitle", 0);
        return Json(selectListOfTests);
    }

    public List<Test> GetAllTests(int gradeLevelId)
    {
        var DB = db.Tests.Where(a => a.ArchiveDateTime == null && a.GradeLevelId == gradeLevelId);
        List<Test> testModel = new List<Test>();
        foreach (var item in DB)
        {
            testModel.Add(new Test{ TestId = item.TestId, TestTitle = item.TestTitle});
        }            
        return testModel;
    }



    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create([Bind(Include = "TestUrlId,TeacherId,TestDateId,School,TestId")] TestUrl testUrl)
    {
        if (ModelState.IsValid)
        {
            testUrl.TestDateId = DateTime.Now.Ticks;
            db.TestUrls.Add(testUrl);
            await db.SaveChangesAsync();
            var newid = testUrl.TestDateId;             
            return RedirectToAction("GetTestUrl", new { id = newid });
        }
        ViewBag.gradeLs = GetGradeLevels();
        return View(testUrl);
    }

我的观点

    @model OkChild.TestUrl

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm(null, null, FormMethod.Post, new { name = "CreateTestURL" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>TestUrl</h4>
        <hr />
        <div class="form-group">
            @Html.LabelFor(model => model.TeacherId, "Name/Email Address", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.TeacherId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.TeacherId, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.School, "Your School", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.School, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.School, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-2">Select your grade please</label>
            <div class="col-md-10">
                @Html.DropDownList("GradeLevelId", (IEnumerable<SelectListItem>)ViewBag.gradeLs as SelectList, "Select a Grade", htmlAttributes: new { value = Request["GradeLevelId"], @class = "form-control", @onchange = "javascript:getTestList(this.value);" })
                @**@
            </div>
        </div>

        <div class="form-group" id="testIddiv">
            <label class="control-label col-md-2">Select your test please</label>
            <div class="col-md-10">
                <select id="TestId" name="tests" class="form-control"></select>
                @Html.ValidationMessageFor(model => model.TestId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" id="SubmitID" class="btn btn-default" />
            </div>
        </div>
    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script type="text/javascript">
        $('#testIddiv').hide();
        $('#SubmitID').hide();

        function getTestList(gradeLevelId) {
            var processmessage = "<option value='0'> Please Wait...</option>";
            $("#tests").html(processmessage).show();

            var url = '@Url.Action("GetTestsbyGradeLevelId")';
            $('#testIddiv').show();
            $.ajax({
                url: url,
                data: { GradeLevelId: gradeLevelId },
                cache: true,
                type: "POST",
                success: function (data) {
                    var select = $("#TestId");
                    select.empty();
                    select.append($('<option/>', { value: "", text: "--Please Select--" }));
                    $.each(data, function (index, itemData) {
                        select.append($('<option/>', {
                            value: itemData.Value,
                            text: itemData.Text
                        }));
                    });

                },
                error: function (response) {
                    alert("error: " + response);
                }
            });
        };
        $('#TestId')
            .change(function () {
                if (this.Value === "--Please Select--") {
                    $('#SubmitID').hide();
                }
                $('#SubmitID').show();
            });
    </script>
}

当我点击提交时,GradeLevelId返回“选择成绩” 并且我的TestId失去了它的选定值。我只需要保存TestId级别级别id只是一个过滤器来查看测试ID。非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您可以手动从 FormCollection 检索这些发布的值。

请确保控件的名称与要从FormCollection中检索的值相同。

<select id="TestId" name="TestId" class="form-control"></select>
                           ^^^^

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(FormCollection formCollection)
{
    if (ModelState.IsValid)
    {
        var teacherId = formCollection["TeacherId"];
        var school = formCollection["School"];
        var gradeLevelId = formCollection["GradeLevelId"];
        var testId = formCollection["TestId"];
                                      ^^^^
        ...
    }
    ViewBag.gradeLs = GetGradeLevels();
    return View(testUrl);
}