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

如何在ASP.NET Core中使用JavaScript实现回发并更新ViewModel

Got it, let's break this down into actionable steps—this is a common tricky scenario in ASP.NET MVC, and I’ve worked through similar postback flows before. Here’s how to make it work smoothly with JavaScript:

Step 1: Hook Up the Trigger Event

First, you need to listen for the selection change on your Person Nature control. Let's assume it's a dropdown with an ID like personNatureDropdown:

document.getElementById('personNatureDropdown').addEventListener('change', async function() {
  // We'll drop the postback logic right here
});

If you’re using jQuery, this simplifies to:

$('#personNatureDropdown').on('change', function() {
  // Postback logic goes here
});
Step 2: Serialize Your ViewModel to JSON

You need to package up all current form data (matching your ViewModel structure) into a JSON object the server can understand.

Using jQuery for quick serialization (convert form data to a proper JSON object):

function serializeFormToJson(formId) {
  const formData = $(`#${formId}`).serializeArray();
  const jsonObj = {};
  formData.forEach(item => {
    jsonObj[item.name] = item.value;
  });
  // Explicitly include the selected Person Nature value to be safe
  jsonObj.PersonNature = $('#personNatureDropdown').val();
  return JSON.stringify(jsonObj);
}

If you’re avoiding jQuery, loop through form elements manually:

function serializeFormToJson(formId) {
  const form = document.getElementById(formId);
  const formData = new FormData(form);
  const jsonObj = {};
  for (const [key, value] of formData.entries()) {
    jsonObj[key] = value;
  }
  return JSON.stringify(jsonObj);
}
Step 3: Send the AJAX Post to the Create Action

Now send the serialized ViewModel to your Create action. Using native Fetch API (no jQuery required):

let isPosting = false; // Prevent duplicate requests
document.getElementById('personNatureDropdown').addEventListener('change', async function() {
  if (isPosting) return;
  isPosting = true;

  const viewModelJson = serializeFormToJson('yourFormId');
  
  try {
    const response = await fetch('/YourController/Create', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val() // Don't skip anti-forgery token!
      },
      body: viewModelJson
    });

    if (!response.ok) {
      throw new Error('Postback failed to complete');
    }

    // Replace current view with the updated one from server
    const updatedViewHtml = await response.text();
    document.getElementById('viewContainer').innerHTML = updatedViewHtml;
  } catch (error) {
    console.error('Error during postback:', error);
    // Add user-friendly error handling here (e.g., a toast message)
  } finally {
    isPosting = false;
  }
});

If you prefer jQuery.ajax:

let isPosting = false;
$('#personNatureDropdown').on('change', function() {
  if (isPosting) return;
  isPosting = true;

  const viewModelJson = serializeFormToJson('yourFormId');
  
  $.ajax({
    url: '/YourController/Create',
    type: 'POST',
    contentType: 'application/json',
    data: viewModelJson,
    headers: {
      'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
    },
    success: function(updatedViewHtml) {
      $('#viewContainer').html(updatedViewHtml);
    },
    error: function(xhr, status, error) {
      console.error('Postback error:', error);
      // Handle error (e.g., show validation messages)
    },
    complete: function() {
      isPosting = false;
    }
  });
});
Step 4: Configure the Server-Side Create Action

Make sure your Create action accepts the ViewModel, processes it, and returns the view with the updated model:

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(YourViewModel model)
{
  // Process the model here (update values, save to database, etc.)
  // Modify the model to reflect your desired changes
  model.UpdatedProperty = "New Value After Processing";
  
  // Return the view with the updated ViewModel
  return View(model);
}
Critical Tips to Avoid Headaches
  • Anti-Forgery Token: Always include the __RequestVerificationToken in headers—ASP.NET MVC blocks POST requests without it to prevent CSRF attacks.
  • View Container: Wrap your entire view content in a div (like <div id="viewContainer">...</div>) so you can easily replace it with the updated HTML from the server.
  • Validation: If your ViewModel has validation attributes, the returned view will automatically show validation errors (just like a regular postback)—no extra work needed.
  • Duplicate Requests: The isPosting flag stops users from triggering multiple postbacks while waiting for the server response.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:09:55