You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将分部视图中ID(loan_no)的值传递至主视图

解决分部视图中loan_no值传递到主视图Ajax请求的问题

先梳理下你代码里的核心问题,咱们一步步来修正:

1. 分部视图中loan_no的取值错误

你的分部视图里loan_no是<span>标签,不是输入框这类表单控件,用$("#loan_no").val()根本拿不到内容,得改用.text()或者.html()来获取它的文本内容。

2. Ajax请求URL的拼接错误

你当前的URL写法"http://localhost:1079/loanapplication/save_Payslip_Info/?loan_no" + current_loan_number少了参数赋值的等于号,正确的拼接应该是"?loan_no=" + current_loan_number,否则后端接收不到正确的参数。

修正后的完整代码

分部视图代码(结构保持,仅确认loan_no元素)

<html>
<head>
</head>
<body>
<table class="label-primary" style="width:110%" id="loan_type">
<tr>
<td>
<div class="floatleft" style="height:50px">
<div class="label" style="font-size:inherit">Loan Name:</div>
<strong>
@Html.DropDownList("loan_code", (SelectList)ViewBag.loanTypes, "--Select Loan Product--", htmlAttributes:new { required = "required",@class = "form-control chosen mandatory", @id ="loan_code"})
@Html.ValidationMessage("loan_code", "", new { @class = "text-danger" })
</strong>
</div>
</td>
<td>
<div class="label" style="font-size:inherit">*Loan No:</div>
<span id="loan_no"></span> <!-- 这里是span标签,用text()取值 -->
</td>
</tr>
</table>
</body>
</html>

主视图修正后的JavaScript代码

function savePayslipInfo() {
    // 修正:用text()获取span的文本内容,trim去掉多余空格
    var current_loan_number = $("#loan_no").text().trim(); 
    console.log(current_loan_number);

    $.ajax({
        type: "POST",
        // 修正URL参数拼接,补上等于号
        url: "http://localhost:1079/loanapplication/save_Payslip_Info/?loan_no=" + current_loan_number,
        data: {
            loan_no: current_loan_number, // 直接复用已获取的变量,避免重复DOM查询
            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');
        },
        // 建议新增错误处理,方便调试问题
        error: function(xhr, status, error) {
            console.error("Save failed:", error);
            $('#msg').html("Failed to save payslip info").fadeIn('slow');
            $('#msg').delay(4000).fadeOut('slow');
        }
    });
}

最后补充两个注意点:

  • 要确保分部视图已经正确渲染到主视图的DOM中,否则$("#loan_no")会找不到元素,返回undefined。
  • 如果loan_no的内容是通过JS动态赋值的,一定要保证在调用savePayslipInfo()之前,这个span的内容已经被正确设置完毕。

内容的提问来源于stack exchange,提问作者Cheruiyot A Kirui

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:38:25