【问题标题】:Is there a way to return Json With ViewBag有没有办法用 ViewBag 返回 Json
【发布时间】:2018-08-05 09:41:33
【问题描述】:

以下代码是将 IntakeName 填充到 Html Helper DropDownlist

控制器代码:

    public ActionResult Index()
    {
        ViewBag.intake = new SelectList(db.Intakes, "IntakeID", "IntakeName");

        return View();
    }

查看代码:

@Html.DropDownList("intake", null, htmlAttributes: new { @class = "form-control" })

默认情况下/在 PageLoad 期间,div id='HiddenIntake' 内的 DropDownList 使用 jquery 隐藏。在文本框 id='UserID' 填充值之后,我将此值传递给控制器​​并更新 Intake DropDownList 并使用 jquery 显示如下:

Jquery Ajax 代码:

$(document).ready(function(){

var x = $('#UserID').val();

            if (x.length > 0) {

                $.ajax({
                    type: "POST",
                    url: "/Payment/IntakeDropDownList",
                    data: { 'values': x },
                    success: function () {
                        $('#HiddenIntake').show();
                    },
                    error: function () {
                        alert('Failed');
                    }
                });

            } else {
                $('#HiddenIntake').hide();
            }
});

控制器代码:

    [HttpPost]
    public ActionResult IntakeDropDownList(int values)
    {
        var result = (from t in db.EnrollmentDetails
                      join i in db.Intakes on t.IntakeID equals i.IntakeID
                      where t.UserID == values
                      select new { i.IntakeID, i.IntakeName }).ToList();


        ViewBag.intake = new SelectList(result, "IntakeID", "IntakeName");

        return Json(result, JsonRequestBehavior.AllowGet);
    }

正如您所见,ViewBag 是更新 Intake DropDownList 但问题是控制器没有返回 View,因此 ViewBag 不起作用。而如果是返回View,那么ajax就不会落入成功函数中。

有没有办法让 ViewBag 工作并进入 ajax 中的成功功能???

【问题讨论】:

  • ViewBag 没有意义。您的return Json(result, JsonRequestBehavior.AllowGet); 是正确的,然后在成功回调中您的循环通过集合并生成新选项(请参阅better way to load 2 dropdown in mvc 示例
  • 然后完全停止使用VIewBag,并使用视图模型并通过使用@DropDownListFor(m => m.YourProperty, Model.YourSelectList)绑定到您的视图模型来正确生成下拉列表
  • 好的,谢谢你的建议,我很期待,顺便说一句,你有什么好的资源来了解如何使用视图模型吗?

标签: javascript jquery ajax asp.net-mvc html-helper


【解决方案1】:

您只能使用 ajax 和 Javascript 来填充您的下拉列表,如下所示。

1.控制器端

 public ActionResult Index()
{
    // remove this line
    // ViewBag.intake = new SelectList(db.Intakes, "IntakeID", "IntakeName");

    return View();
}

2。查看端:AJAX

var x = $('#UserID').val();

        if (x.length > 0) {

            $.ajax({
                type: "POST",
                url: "/Payment/PopulateIntakeDropDown",
                data: { 'values': x },
                success: function (data) {
                   // test some stuff here to see if there is no errors 
                   // and at least an element in data
                   // then build your dropdown using javascript as following
                   // and i assume that you have an <select> element generated
                   // by your @Html.DropdownList helper with Id : intake   
                   // so after all that, you can loop inside data (returned from controller)
                   // and for each element inside we will create an <option value=""></option> 
                   // and do not forget to clear all "option" tags before populating 
                    $('#intake option').remove()
                    $.each(data, function(index,elementIntake){                          
                    $('#intake').append('<option value="' + elementIntake.IntakeID + '">' + elementIntake.IntakeName + '</option>')   
                       })


                },
                error: function () {
                    alert('Failed');
                }
            });

        } else {
            // depends of your personal choice of UI behavior, keep or remove
            // $('#HiddenIntake').hide();
        }
     });

3.控制器 POST 方法

[HttpPost]
public ActionResult PopulateIntakeDropDown(int values)
{
    var result = (from t in db.EnrollmentDetails
                  join i in db.Intakes on t.IntakeID equals i.IntakeID
                  where t.UserID == values
                  select new { i.IntakeID, i.IntakeName }).ToList();

    // remove this line
    // ViewBag.intake = new SelectList(result, "IntakeID", "IntakeName");

    return Json(result, JsonRequestBehavior.AllowGet);
}

【讨论】:

  • 谢谢这很好地解决了这个问题。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-12
  • 2012-01-06
  • 2016-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多