javascript - 如何将 ViewBag 从 Controller 传递到 View (Ajax Url)

标签 javascript c# json viewbag

** Controller 代码 **

我的 Controller 和方法 get_current_LoanNumber 中有以下代码

public JsonResult (string loan_code)
{
    try
    {
        using (sqlConnection)
        {
            dynamic loanno = sqlConnection.Query("get_loan_number", new {loan_code }, 
            commandType: CommandType.StoredProcedure).SingleOrDefault();

            ViewBag.currentLoanNumbe= loanno.LoanNo;

            return Json(loanno, JsonRequestBehavior.AllowGet);
        }
    }
    catch (Exception)
    {
        throw;
    }
}

查看代码 这是 View 中的代码,JavaScript 函数 savePayslipInfo 发出 Ajax 请求。

 function () {

    console.log('@ViewBag.currentLoanNumbe');
    $.ajax({
        type: "POST",
        url: "http://localhost:1079/loanapplication/save_Payslip_Info/?loan_no" + '@ViewBag.currentLoanNumbe',
        data: {
            //loan_no: $(loan_no).val(),
            basic_salary: $("#basic_salary").val(),
            house_allowance: $("#house_allowance").val(),
            other_allowance: $("#other_allowance").val(),
            other_payment: $("#other_payment").val(),
            total_deduction: $("#total_deduction").val()
        },
        success: function () {
            $('#msg').html("Payslip info saved successfully").fadeIn('slow');
            $('#msg').delay(4000).fadeOut('slow');
        }
    });
}

最佳答案

这不是 MVC 的工作原理。您没有从操作方法返回 View 。您正在返回一个 JSON。因此,没有任何 View 与操作方法相关联。您本质上所做的是将操作方法​​用作 API,并使用 AJAX 从 Javascript 调用它,这与从操作返回并绑定(bind) View 不同。您的 ViewBag 将无法访问,因为您在此处使用的 View 未由问题中的 Action 方法呈现。

关于javascript - 如何将 ViewBag 从 Controller 传递到 View (Ajax Url),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56816673/

相关文章:

c# - 如何在通用扩展方法中使用字符串列名称在 IQueryable 上应用 OrderBy?

javascript - 隔离 JSON 中具有相似属性的对象

javascript - Paypal 快速结账 : Successful transaction but cannot show the order detail in seller account

javascript - 为什么每个按钮只能工作一次?

javascript - 如何比较 vue.js 中的属性值

c# - 我可以从扩展方法返回不同类型吗

javascript - 在 chart.js 中使用 JSON 文件

javascript - 防止在网站中使用触摸屏进行缩放(IE 11、Win 10)

javascript - 在 Rails 中使用 link_to 发送表单参数

javascript - 动态显示所有页面的页面名称到index.html