使用JSON Data JQuery在MVC Razor View页面上更新ViewBag数据

时间:2017-01-23 15:38:15

标签: jquery json asp.net-mvc razor

我正在尝试使用JSON数据更新MVC Razor视图页面上的ViewBag。但它没有更新ViewBag或Div。当我查看成功的警报时,它显示更新的值,但在页面内,它不会更改值。最初页面加载时,它显示的是值。

我的JQuery代码是 -

$(document).ready(function ()
    {
        $('#ddl2').change(function (e)
        {
            e.preventDefault();
            var str_test = $("#v_ddl2 :selected").text();           
            var data1 = {str_test: str_test }; 
            var url = '@Url.Action("ddl_2")?id=' + id;

            $.post(url, data1, function (data)
            {
                $('#nav_div').html(data);
                alert(JSON.stringify(data)); // ALERT showing the updated data
            });

        });
    });

控制器 -

public JsonResult ddl_2(string str_test)
    {
        GetDat(str_test);

        return Json(new { success = true, ViewBag.str_display });
    }

HTML -

<div id='#nav_div'>@ViewBag.str_display</div>

有人可以帮我查看ViewBag或Div如何显示更新的数据。

由于

2 个答案:

答案 0 :(得分:0)

您的ID包含&#39;#&#39;字符

<div id='nav_div'>@ViewBag.str_display</div>

答案 1 :(得分:0)

您可以尝试以下。按如下方式更改您的退货声明

signed

并按如下所示更改您的javascript(jquery)

public JsonResult ddl_2(string str_test)
{
      GetDat(str_test);

      return Json(new { success = true, display = ViewBag.str_display });
}

并将您的HTML更改为 $.post(url, data1, function (data) { $('#nav_div').html(data.display); alert(JSON.stringify(data.display)); // ALERT showing the updated data });