Tôi có kiểu xem với một từ bao gồm một tập hợp các hộp kiểm. Tôi cần các hộp kiểm tra để ánh xạ tới một mảng khi ràng buộc trong phương thức post back của controller của tôi.ASP.NET MVC - Không thể liên kết mảng để xem mô hình
Đây là mô hình xem.
@model TMDM.Models.TestSeriesCreateViewModel
@{
ViewBag.Title = "Create";
}
<h2>Create a Test Series</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
@Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</div>
<h3>Which Test Collections are in this Test Series?</h3>
<div class="editor-field">
@{
var i = 0;
foreach (var testCollection in Model.TestCollections)
{
<input type="checkbox" id="ChosenTestCollectionIds[@i]" name="ChosenTestCollectionIds[@i]" value="@testCollection.Id" />
<span>@testCollection.Title</span>
<br />
i++;
}
}
</div>
<p>
<input type="submit" value="Save" class="medium green awesome" />
@Html.ActionLink("Cancel", "Index", "TestSeries", null, new { @class = "medium black awesome" })
</p>
</fieldset>
Biểu mẫu hiển thị tốt, tôi đã chọn hộp kiểm nguồn và mỗi đầu ra có một số khác cho trường id và tên của chúng.
<input type="checkbox" id="ChosenTestCollectionIds[0]" name="ChosenTestCollectionIds[0]" value="5" />
<input type="checkbox" id="ChosenTestCollectionIds[1]" name="ChosenTestCollectionIds[1]" value="6" />
//etc...
Đây là mô hình xem.
public class TestSeriesModel
{
public int Id { get; set; }
public string Title { get; set; }
}
public class TestSeriesCreateViewModel : TestSeriesModel
{
public List<ITestCollectionDataObject> TestCollections { get; set; }
public int[] ChosenTestCollectionIds { get; set; }
}
Vấn đề tôi gặp phải là khi biểu mẫu đăng lại mảng ChosenTestCollectionIds trở về null. Tôi làm gì sai ở đây?
ĐÁP
Tôi đã làm việc ra làm thế nào để làm điều đó:
<input type="checkbox" id="[@i]" name="ChosenTestCollectionIds" value="@testCollection.Id" />
Xin chào. Tôi có thể giúp bạn nhiều hơn trong một vài giờ, nhưng trong khi đó bạn muốn tất cả các hộp kiểm có cùng thuộc tính "tên" và "id" khác nhau. Hãy thử và xem nếu nó hoạt động. –
@payntbrush: Hoàn hảo. 1 để đánh bại tôi với nó bằng 2. –