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

咨询MVC模型Ajax绑定及局部视图JS函数调用报错问题

Hey there! Let's work through your two issues: the "BulkConfirm() is not defined" error, and getting your MVC model properly bound with the Ajax call.

1. Fixing the "BulkConfirm() is not defined" Error

The problem here is that the @section script block in your partial view probably isn't being rendered by your layout page. Partial views don't automatically push their sections into the layout—only the main view's sections get picked up by @RenderSection("script", ...) in your layout.

Quick Fixes:

  • Best Option: Ditch the @section script wrapper and put your <script> tag directly in the partial view, right at the end (before the closing modal div). This way, the script loads along with the partial view's HTML, so the function is available when the button is clicked.
  • Alternative (If You Prefer Sections): Make sure your main layout has @RenderSection("script", required: false), but note this won't work if you load the partial view via Ajax later on.

2. Properly Binding Your MVC Model to the Ajax Call

Your current line var data=@Model.updatedDatas is just outputting the C# object's string representation (like System.Collections.Generic.List...) instead of valid JSON, which is why the model binding fails. Here's how to fix this:

Step 1: Turn Your C# Model into Valid JSON

Use Json.Serialize (for ASP.NET Core) or Json.Encode (for MVC 5) to convert your model to a JSON string, and @Html.Raw to prevent HTML encoding from breaking it:

var updatedDatas = @Html.Raw(Json.Serialize(Model.updatedDatas));

Step 2: Configure the Ajax Call Correctly

  • Set contentType: "application/json; charset=utf-8" so MVC knows you're sending JSON data.
  • Use JSON.stringify() to convert the JavaScript object into a JSON string for the request body.
  • Include the AntiForgery Token if your controller action uses [ValidateAntiForgeryToken] (you should use this for all POST requests to prevent CSRF attacks).

Step 3: Add the AntiForgery Token to Your Form

Drop @Html.AntiForgeryToken() inside your <form> tag to generate the token needed for validation:

<form id="test">
    @Html.AntiForgeryToken()
    <!-- Your table code stays the same -->
</form>

Full Updated Partial View

Here's the complete fixed partial view:

@model Manual_Tag_Entry.ViewModel.ModelAccessor
<div class="modal-header">
 <h3 class="modal-title" id="exampleModalLabel">Do you want to update following information?</h3>
 <button type="button" class="close" data-dismiss="modal" aria-label="Close">
 <span aria-hidden="true">&times;</span>
 </button>
</div>
<form id="test">
    @Html.AntiForgeryToken()
 <table class="table table-striped table-bordered" width="80%">
 <thead>
 <tr>
 <th>Tag Name</th>
 <th>Tag Old Value</th>
 <th>Tag New Value</th>
 </tr>
 </thead>
 <tbody>
 @if (Model.updatedDatas != null)
 {
 foreach (var item in Model.updatedDatas)
 {
 <tr>
 <td> @item.TagName </td>
 <td> @item.OldTagValue </td>
 <td> @item.NewTagValue </td>
 </tr>
 }
 }
 </tbody>
 </table>
</form>
<div class="modal-footer">
 <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
 <button type="button" class="btn btn-primary" onclick="BulkConfirm()">Confirm Update</button>
</div>

<script>
 function BulkConfirm() {
 debugger;
 // Convert C# model to a valid JavaScript object
 var updatedDatas = @Html.Raw(Json.Serialize(Model.updatedDatas));
 
 $.ajax({
 type: 'POST',
 url: '@Url.Action("BulkUpdateConfirmation", "Home")',
 contentType: "application/json; charset=utf-8",
 data: JSON.stringify(updatedDatas),
 // Include anti-forgery token for security
 headers: {
 RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
 },
 success: function(response) {
 // Handle successful update
 alert('Update completed successfully!');
 $("#myModal").modal('hide');
 },
 error: function(xhr, status, error) {
 // Log and handle errors
 console.error('Update failed:', error);
 alert('Update failed. Please try again later.');
 }
 });
 }
</script>

Controller Action Example

Make sure your controller action is set up to receive the model correctly:

using Microsoft.AspNetCore.Mvc; // For ASP.NET Core
// using System.Web.Mvc; // For MVC 5

namespace Manual_Tag_Entry.Controllers
{
    public class HomeController : Controller
    {
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult BulkUpdateConfirmation(List<YourUpdatedDataModel> updatedDatas)
        {
            // Replace YourUpdatedDataModel with the actual type of items in your updatedDatas list
            // Add your bulk update logic here (save to database, etc.)
            
            return Json(new { success = true });
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:14:10