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

多局部视图页面中Create Invoice按钮的Onclick事件处理

Since you're using @Html.ActionLink (which renders an <a> tag) in your partial views, here are practical ways to attach an onclick event handler to your "Create Invoice" button, depending on your needs:

1. Add Inline onclick Attribute Directly

For simple, immediate logic, you can include the onclick attribute in the HTML parameters of your ActionLink:

<div class="button-bar col-md-2">
    @Html.ActionLink(
        @Resources.Common.CreateInvoice, 
        "EditLotDamage", 
        "TimberMonitor", 
        new { /* Your route params, e.g., Id = 0, LotId = ViewBag.Id */ }, 
        new { @class = "btn btn-success", onclick = "handleCreateInvoice(event);" }
    )
</div>

Then define your handler in a script tag (either in your view or a dedicated JS file):

function handleCreateInvoice(event) {
    // Add your custom logic here (e.g., validation, confirmation)
    console.log("Create Invoice button clicked!");
    
    // Uncomment below to block default navigation (if you want to use AJAX instead)
    // event.preventDefault();
    // Example AJAX call would go here
}

2. Use Event Delegation (For Dynamically Loaded Partials)

If your partial views load after the initial page render (e.g., via AJAX), direct event listeners might fail. Use event delegation to attach the handler to a stable parent element:

document.addEventListener('DOMContentLoaded', function() {
    // Target a parent element that exists on page load (like your .row container)
    document.querySelector('.row').addEventListener('click', function(event) {
        // Check if the clicked element is your Create Invoice button
        const targetBtn = event.target.closest('.btn-success');
        if (targetBtn && targetBtn.textContent.trim() === '@Resources.Common.CreateInvoice') {
            // Your custom logic here
            console.log("Create Invoice clicked (delegated handler)!");
            
            // Optional: Prevent default navigation
            // event.preventDefault();
        }
    });
});

If you need to bypass default anchor navigation entirely (e.g., for an AJAX-only workflow), swap the ActionLink for a regular button:

<div class="button-bar col-md-2">
    <button type="button" class="btn btn-success" onclick="submitInvoiceCreation()">
        @Resources.Common.CreateInvoice
    </button>
</div>

Then implement the logic with proper ASP.NET MVC safeguards:

function submitInvoiceCreation() {
    // Example: AJAX POST to create invoice
    fetch('/TimberMonitor/CreateInvoice', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': '@Html.AntiForgeryToken()' // Critical for CSRF protection
        },
        body: JSON.stringify({ LotId: @ViewBag.Id }) // Pass your data here
    })
    .then(response => response.json())
    .then(data => {
        console.log("Invoice created successfully!", data);
        // Refresh partial view or update UI as needed
    })
    .catch(error => console.error("Error creating invoice:", error));
}

Quick Tips:

  • If you keep the ActionLink, your handler will run before the browser navigates to the target action unless you call event.preventDefault().
  • Always include CSRF tokens when making POST requests to avoid security vulnerabilities.
  • For complex workflows, separate your JavaScript logic into external files instead of inline handlers for better maintainability.

内容的提问来源于stack exchange,提问作者Kar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:04:23