我有一个通过 EditorTemplate 呈现的下拉列表。该属性在验证类中有 UIHints 并正确显示,但是当我查看 HTML 时,控件的名称是 PropertyType.PropertyName 而不仅仅是 PropertyName。
这可以防止模型绑定。
我也无法将选定的值返回给视图。
我该如何解决这个问题?
更新有关详细信息,请参阅下面的答案。
视图模型
public partial class HouseholdEditViewModel
{
public int householdID { get; set; }
public int familyID { get; set; }
public string address { get; set; }
public HousingTypeDropDownViewModel housingType { get; set; }
public KeyworkerDropDownViewModel keyworker { get; set; }
public string attachmentDate { get; set; }
public bool loneParent { get; set; }
public string familyPhoneCode { get; set; }
public string familyPhone { get; set; }
}
下拉视图模型
public class HousingTypeDropDownViewModel
{
public int housingTypeID { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
编辑器模板
@model WhatWorks.ViewModels.HousingTypeDropDownViewModel
@Html.DropDownListFor(h => h.housingTypeID, new SelectList(Model.Items, "Value", "Text"))
看法
using (Html.ControlGroupFor(property.Name))
{
@Html.Label(property.GetLabel(), new { @class = "control-label" })
<div class="controls">
@Html.Editor(property.Name, new { @class = "input-xlarge" })
@Html.ValidationMessage(property.Name, null, new { @class = "help-inline" })
</div>
}
HTML
<div class="control-group">
<label class="control-label" for="Housing_Type">Housing Type</label>
<div class="controls">
<select data-val="true" data-val-number="The field housingTypeID must be a number." data-val-required="The housingTypeID field is required." id="housingType_housingTypeID" name="housingType.housingTypeID">
<option value="1">Owner Occupied</option>
<option value="2">Rented - Social Landlord</option>
</select>
<span class="field-validation-valid help-inline" data-valmsg-for="housingType" data-valmsg-replace="true"></span>
</div>
</div>