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



我正在尝试使用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 如何显示更新的数据。

谢谢

您可以尝试以下操作。 更改您的返回语句,如下所示

public JsonResult ddl_2(string str_test)
{
      GetDat(str_test);
      return Json(new { success = true, display = ViewBag.str_display });
}

并更改您的JavaScript(jquery),如下所示

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

并将您的 HTML 更改为<div id='nav_div'>@ViewBag.str_display</div>

您的 ID 包含"#"字符

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

最新更新