DropDown not being set when loading edit page, but rest of view model properties are set
I have these two tables in my database, named Vendors and VendorPriceBreaks:
Vendors
-----------------
VendorID (PK)
Name
VendorPriceBreaks
-----------------
VendorPriceBreakID (PK)
VendorID (FK)
Price
PaymentTypeID (FK)
I have a single view page to add a Vendor and VendorPriceBreaks at the same time.
Here's my VendorsViewModel:
public class VendorsViewModel
{
[HiddenInput(DisplayValue = false)]
public int VendorId { get; set; }
public string Name { get; set; }
public IEnumerable<VendorPriceBreaksViewModel> VendorPriceBreaks { get; set; }
}
Here's my 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; }
}
Here's the view page for Vendors:
<%: Html.TextBoxFor(m => m.Name)%>
<table id="dynamic-rows" cellpadding="0" cellspacing="0">
<% foreach (var item in Model.VendorPriceBreaks)
Html.RenderPartial("VendorPriceBreakRow", item);
%>
</table>
And here's my control:
<%@ 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>
When I'm editing a vendor and the price breaks are loaded, the Price is set, but not the PaymentType value in the dropdown.
Here's the function for when editing a Vendor:
public ActionResult Edit(int id)
{
var vendor = _adminRepository.GetVendor(id);
List<VendorPriceBreaksViewModel> priceBreakssViewModels = new List<VendorPriceBreaksViewModel>();
foreach (VendorPriceBreak priceBreak in vendor.Ve开发者_JAVA百科ndorPriceBreaks)
{
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);
}
So the data for the dropdown is being loaded, but the selected value isn't being set. But the Price value is being set in the textbox.
I'm not sure what's going on.
Try using this code instead:
<%= Html.DropDownListFor(m => m.PaymentTypeId,
new SelectList(Model.PaymentTypes, "PaymentTypeID", "Name", Model.PaymentTypeId),
"- Select a Payment Type -")%>
More detailed analysis is here - DropDownListFor not binding on Edit View with repeating items (List).
精彩评论