我的数据库中有这两个表,名为Vendors和VendorPriceBreaks:
Vendors
-----------------
VendorID (PK)
Name
VendorPriceBreaks
-----------------
VendorPriceBreakID (PK)
VendorID (FK)
Price
PaymentTypeID (FK)
我有一个视图页面可以同时添加Vendor和VendorPriceBreaks。
这是我的VendorsViewModel:
public class VendorsViewModel
{
[HiddenInput(DisplayValue = false)]
public int VendorId { get; set; }
public string Name { get; set; }
public IEnumerable<VendorPriceBreaksViewModel> VendorPriceBreaks { get; set; }
}
这是我的VendorPriceBreaksViewModel:
public class VendorPriceBreaksViewModel
{
[HiddenInput(DisplayValue = false)]
public int VendorPriceBreakId { get; set; }
public double? Price { get; set; }
public int? PaymentTypeId { get; set; }
public IEnumerable<PaymentType> PaymentTypes { get; set; }
}
以下是供应商的视图页面:
<%: Html.TextBoxFor(m => m.Name)%>
<table id="dynamic-rows" cellpadding="0" cellspacing="0">
<% foreach (var item in Model.VendorPriceBreaks)
Html.RenderPartial("VendorPriceBreakRow", item);
%>
</table>
这是我的控制:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<CopyCraft.WebUI.Areas.Admin.Models.VendorPriceBreaksViewModel>" %>
<tr class="dynamic-row">
<% using(Html.BeginCollectionItem("vendorPriceBreaks")) { %>
<td>$<%= Html.TextBoxFor(m => m.Price) %></td>
<td><%= Html.DropDownListFor(m => m.PaymentTypeId, new SelectList(Model.PaymentTypes, "PaymentTypeID", "Name"), "- Select a Payment Type -")%></td>
<% } %>
</tr>
当我编辑供应商并加载价格中断时,会设置价格,但不会设置下拉列表中的PaymentType值。
以下是编辑供应商时的功能:
public ActionResult Edit(int id)
{
var vendor = _adminRepository.GetVendor(id);
List<VendorPriceBreaksViewModel> priceBreakssViewModels = new List<VendorPriceBreaksViewModel>();
foreach (VendorPriceBreak priceBreak in vendor.VendorPriceBreaks)
{
priceBreaksViewModels.Add(new VendorPriceBreaksViewModel
{
Price = sheetPrice.Price,
PaperUnitTypeId = sheetPrice.PaperUnitTypeID,
PaperUnitTypes = _adminRepository.GetAllPaperUnitTypes()
}
);
}
var viewModel = new VendorsViewModel
{
VendorId = vendor.VendorID,
Name = vendor.Name,
VendorPriceBreakSheetPrices = sheetPricesViewModels
};
return View(viewModel);
}
因此正在加载下拉列表的数据,但未设置所选值。但价格值正在文本框中设置。
我不确定发生了什么。
答案 0 :(得分:1)
请尝试使用此代码:
<%= Html.DropDownListFor(m => m.PaymentTypeId,
new SelectList(Model.PaymentTypes, "PaymentTypeID", "Name", Model.PaymentTypeId),
"- Select a Payment Type -")%>
此处有更详细的分析 - DropDownListFor not binding on Edit View with repeating items (List)。