如何获取动态加载Partial Views的BranchView模型数组?
Hey David, I’ve tackled this exact scenario a few times with ASP.NET MVC, so let’s walk through the steps to get your dynamic partial views submitting as a BranchView[] array correctly.
Backend Setup
First, let’s make sure your backend is configured to handle both loading the partials and receiving the array.
1. Define Your BranchView Model
Make sure your model has all the properties you need (adjust based on your actual requirements):
public class BranchView { public int Id { get; set; } public string BranchName { get; set; } public decimal AllocatedAmount { get; set; } // Add any other properties here }
2. Create the Partial View Loader Action
This action will return a partial view with a properly prefixed model, so the input names are formatted for array binding:
public ActionResult LoadSpread(int index) { // Initialize a new BranchView (or populate with default data if needed) var branchModel = new BranchView(); // Set the HTML field prefix so inputs get named like `branchViews[0].BranchName` ViewData.TemplateInfo.HtmlFieldPrefix = $"branchViews[{index}]"; return PartialView("_BranchPartial", branchModel); }
3. Create the Partial View (_BranchPartial.cshtml)
Use Razor helpers to generate inputs that follow the array naming convention:
@model BranchView <div class="branch-container mb-3"> @Html.HiddenFor(m => m.Id) <div class="form-group"> @Html.LabelFor(m => m.BranchName) @Html.TextBoxFor(m => m.BranchName, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.BranchName) </div> <div class="form-group"> @Html.LabelFor(m => m.AllocatedAmount) @Html.TextBoxFor(m => m.AllocatedAmount, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.AllocatedAmount) </div> <button type="button" class="btn btn-sm btn-danger remove-branch">Remove Branch</button> </div>
4. Create the Submission Action
This action will accept the BranchView[] array directly thanks to the proper input naming:
[HttpPost] public ActionResult GetInitializedBranch(BranchView[] branchViews) { // branchViews will contain all the dynamically added partial view data if (branchViews != null && branchViews.Length > 0) { // Do your business logic here (save to DB, process data, etc.) } // Redirect or return a response as needed return RedirectToAction("Index"); }
Frontend Implementation
Now let’s handle loading the partials dynamically and submitting the form.
1. Main Form Structure
Add a container for your dynamic partials and controls to add/remove them:
<form id="branchForm" action="@Url.Action("GetInitializedBranch")" method="post"> <div id="branchViewsContainer"> <!-- Dynamically loaded partials will go here --> </div> <button type="button" id="addBranchBtn" class="btn btn-primary mb-3">Add New Branch</button> <button type="submit" class="btn btn-success">Submit All Branches</button> </form>
2. JavaScript for Dynamic Loading & Submission
Use jQuery to load partials, track indexes, and handle removal:
$(document).ready(function() { let currentBranchIndex = 0; // Add a new branch partial when the button is clicked $('#addBranchBtn').click(function() { $.get('/Home/LoadSpread', { index: currentBranchIndex }, function(partialHtml) { $('#branchViewsContainer').append(partialHtml); // Reinitialize unobtrusive validation for the new partial (if using validation) $.validator.unobtrusive.parse('#branchViewsContainer'); currentBranchIndex++; }); }); // Remove a branch (use event delegation since elements are dynamic) $('#branchViewsContainer').on('click', '.remove-branch', function() { $(this).closest('.branch-container').remove(); // Note: ASP.NET MVC allows non-consecutive indexes in array binding, so no need to reindex unless you want to }); // Optional: AJAX form submission (instead of default form post) $('#branchForm').submit(function(e) { e.preventDefault(); $.post($(this).attr('action'), $(this).serialize(), function(response) { // Handle success response (e.g., show message, reload page) alert('Branches submitted successfully!'); }); }); });
Key Notes to Avoid Issues
- Input Naming: The critical part is setting
ViewData.TemplateInfo.HtmlFieldPrefixin theLoadSpreadaction. This ensures Razor generates input names likebranchViews[0].BranchName, which ASP.NET MVC uses to bind to the array. - Validation: If you’re using unobtrusive validation, you need to reparse the validation rules after loading each partial (as shown in the JS code) so the new inputs are validated.
- Index Gaps: ASP.NET MVC’s model binder doesn’t mind non-consecutive indexes (e.g., 0, 2, 3). It will still bind all valid entries into the array. If you want consecutive indexes for cleanliness, you can write a function to reindex the input names after deletion, but it’s not required.
内容的提问来源于stack exchange,提问作者David

