我的应用程序有一个问题,病例尝试通过示例说明,我有一个表单,这种形式存在几个文本框和下拉列表.为了可重用性,我将3个下拉列表合并到局部视图中,这个部分视图我用@
Html.Action加载,这可以正常工作,当我启动表单时,我看到一切似乎应该是,尽管我不知道为什么,但是那些需要下拉列表直接显示为红色开始,表示为必填字段.
@H_502_2@但是当我填写所有内容时,我从下拉列表中选择值,然后单击确定,下拉列表中的值为NULL.
@H_502_2@我认为一个代码示例会更容易理解:
@H_502_2@主要型号:
public class FormModel { [required] public string UserName { get; set; } [required] [Display(Name = "Birthdate")] public DateTime? Birthdate { get; set; } //This is what i'm talking about,that is not being set,the location public Location Location { get; set; } }@H_502_2@这是位置类,然后传递给局部视图,通常我认为应该设置,它看起来像这样:
public class Location { [required] [Display(Name = "Country")] public string CountryId { get; set; } [required] [Display(Name = "Region")] public string RegionId { get; set; } [required] [Display(Name = "City")] public string CityId { get; set; } }@H_502_2@现在我们有一个局部视图的位置:
@model TestWebsite.Models.Location <tr> <td class="editor-label"> @Html.LabelFor(m => m.CountryId) </td> <td class="editor-field"> @Html.DropDownListFor(m => m.CountryId,Model.Countries,"---select--",null) </td> <td> @Html.ValidationMessageFor(m => m.CountryId) </td> </tr> <!-- Region --> <tr> <td class="editor-label"> @Html.LabelFor(m => m.RegionId) </td> <td class="editor-field"> @Html.DropDownListFor(m => m.RegionId,Enumerable.Empty<SelectListItem>(),null) </td> <td> @Html.ValidationMessageFor(m => m.RegionId) </td> </tr> <!-- City --> <tr> <td class="editor-label"> @Html.LabelFor(m => m.CityId) </td> <td class="editor-field"> @Html.DropDownListFor(m => m.CityId,null) </td> <td> @Html.ValidationMessageFor(m => m.CityId) </td> </tr>@H_502_2@那么我们将这个局部视图称为这样的形式:
@Html.Action("LocationGroup","Account",Model.Location)@H_502_2@最后在控制器:
[ChildActionOnly] public ActionResult LocationGroup(Location model) { model.Countries = GetCountries(); return PartialView("_LocationView",model); }@H_502_2@我知道这是很多代码,但我希望你能帮助我…
解决方法
我想你应该使用编辑器模板:
@model TestWebsite.Models.FormModel @using(Html.BeginForm()) { @Html.EditorFor(x => x.Location) <input type="submit" value="save"/> }@H_502_2@并添加部分内部〜/ Views / [ControllerName] /EditorTemplates/Location.cshtml或〜/ Views / Shared / EditorTemplates / Location.cshtml @H_502_2@模板代码:
@model TestWebsite.Models.Location <tr> <td class="editor-label"> @Html.LabelFor(m => m.CountryId) </td> <td class="editor-field"> @Html.DropDownListFor(m => m.CountryId,null) </td> <td> @Html.ValidationMessageFor(m => m.CityId) </td> </tr>@H_502_2@但是,如果您希望在某些位置部分(不遵循约定),您可以指定位置:
@Html.EditorFor(x => x.Location,"~/Views/SpecifyLocation/_Location.cshtml")