推荐的方法是什么,用于动态加载部分视图,其中包含来自数据库的内容的下拉列表

What is the recommended method, for dynamically loading a partial view, that has dropdowns with content from db

我有一个列表,我加载到我的编辑页面上,可以添加更多。局部视图有许多下拉菜单,目前通过 ViewBag 填充。在初始加载时一切正常,但是,当我使用添加通过 ajax 附加另一个部分时,下拉菜单会抛出一个特定的错误。

'The ViewData item that has the key 'UserTypeId' is of type 'System.Int32' but must be of type 'IEnumerable'.'

我觉得一定有更好的方法可以做到这一点,但我的谷歌搜索失败了。任何帮助将不胜感激。

控制器

//UserTypes is List<UserType>
//int ID
//string Name 
ViewBag.ListUserTypes = new SelectList(UserTypes, "ID", "Name");
        public ActionResult CreateNewQuotesMentions()
    {
        var model = new QuoteMention();

        return PartialView("~/Views/master/newsalert/_QuotesMentions.cshtml", model);
    }

视图模型

 public List<QuoteMention> QuotesMentions { get; set; }

景色

<div id="QuotesMentions">
    @foreach (var item in Model.QuotesMentions)
    {
        @Html.Partial("~/Views/Master/NewsAlert/_QuotesMentions.cshtml", item)
    }
</div>
<div>
    <input type="button" name="addQuotesMentions" id="addQuotesMentions" value="Add" />
</div>

.JS

$("#addQuotesMentions").on('click', function () {

    $.ajax({
        type: "GET",
        url: '/en/master/news-alert/CreateNewQuotesMentions',
        success: function (partialView) {
            $('#QuotesMentions').append(partialView);
        }
    });

});

$(document).on('click', ".btn-delete", function (e) {
    var container = $(this).closest('.box');
    var id = container.data('id');
    if (!id) {
        container.remove();
    } else {
        // see notes below
    }

});

ThePartialView

@model Portal.Business.QuoteMention

@using (Html.BeginCollectionItem("NewQuotes"))
{
<div class="col-sm-4">
    @Html.LabelFor(m => m.UserType, new { @class = "control-label" })
    @Html.DropDownListFor(m => m.UserTypeId, (SelectList)ViewBag.ListUserTypes,
    "-- Please Select --", new { @class = "form-control", style="width:100%;"}
    )
</div>

不幸的是,您的 ViewBag 在您的 CreateNewQuotesMentions 方法执行时被清理了。

可能的解决方法是 re-populate ViewBag.ListUserTypes。 我还建议看一下 TempData。在某些情况下它可以拯救你。你可以阅读它 here.