如何在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:
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 });
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); }
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; } }); });
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); }
- Anti-Forgery Token: Always include the
__RequestVerificationTokenin 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
isPostingflag stops users from triggering multiple postbacks while waiting for the server response.
内容的提问来源于stack exchange,提问作者Master JR

