更改下拉列表中的调用操作并发送模型以查看

Call an action in dropdownlist changed and send a model to view

我正在尝试在下拉列表中调用一个控制操作,选择的项目已更改,我使用 jquery:

  @Html.DropDownListFor(model => model.SelectedItemType.RowId, new SelectList(Model.ItemTypes, "RowId", "ItemTypeName")
                , htmlAttributes: new { @class = "form-control SelectList",@id="itemTypesDropDown", style = "height:300px", @size = 5
                }))

 $("#itemTypesDropDown").change(function () {
        var selectedValue = $('#itemTypesDropDown').val();
        $.post('@Url.Action("Select", "Home")', { selectedRowId: selectedValue }, function (data) {
        });
    }); 

控制动作为:

  [HttpPost]
    public ActionResult Select(long selectedRowId)
    {
        SetIndexViewDatas();

        var itemtypemodel = new ItemTypeViewModel
        {
            ItemTypes = _db.Inv_ItemType.Select(x => x).ToList(),
            SelectedItemType = _db.Inv_ItemType.FirstOrDefault()
        };
        return View("Index", itemtypemodel);
    }

和index.cshtml:

  <div class="row">
        <div class="form-group verticalAlign">
            @Html.LabelFor(model => model.SelectedItemType.ItemTypeName, "Attribute Name", htmlAttributes: new { @class = "control-label col-md-4 lable" })
            <div class="col-md-8">
                @Html.EditorFor(model => model.SelectedItemType.ItemTypeName, "Attribute Name", new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.SelectedItemType.ItemTypeName, "", new { @class = "text-danger" })
            </div>
        </div>
        <br />

它工作正常,在选择的项目改变后它调用 select 操作和 post itemtypemodelindex 视图,但问题是它没有加载数据在index,我哪里做错了?

您拨打了 ajax 电话,这意味着您保持在同一页面上。您的方法需要 return 部分视图,并且确实应该是 GET。然后你需要用 html 更新 DOM 你的 returning

public ActionResult Select(long selectedRowId)
{
    ....
    return PartialView("Index", itemtypemodel);
}

在视图中,包含一个元素作为占位符以呈现您的局部视图 return

<div id="myContent"></div>

并将脚本修改为

$("#itemTypesDropDown").change(function () {
    $.post('@Url.Action("Select", "Home")', { selectedRowId: $(this).val() }, function (data) {
        $('#myContent').html(data);
    });
});

或者,如果您不想更新当前页面,而是想重定向到另一个页面,请不要使用 ajax(只需使用正常的提交和重定向)。