首页 > 解决方案 > MVC 中带有 @Html.DropDownListFor 字段的可编辑 HTML 表

问题描述

我想在具有可编辑字段的 .net MVC 中创建 HTML 表格页面。我可以为 TextBoxFor 字段执行此操作。在提交页面后控制器方法从表中接收值。我在使用 DropDownListFor 时遇到问题。页面正在使用 DropDownListFor 字段呈现,但在提交后控制器方法接收模型对象,其属性中没有任何数据。在下面的代码片段中,SaveMyItems 控制器操作方法确实接收模型对象,其属性设置为空值。

这是我的模型类

public class ItemsEntryModel
{
  public ItemModel Item { get; set; }
  public List<MyItemOptions> MyItemsOptionList { get; set; }  
  //individual field of HTML table      
}

public class ItemModel
{
  public int ID { get; set; }
  public string ItemName { get; set; }
}

public class MyItemOptions
{
  public int ID { get; set; }
  public int MyItemOptionUniqueNo { get; set; }
  public string OptionName { get; set; }
  public MyItemSubOptions SelectedItemSubOption { get; set; }
  public List<MyItemSubOptions> MyItemSubOptionsList { get; set; } 
  //bind in individual dropdown of field
}

public class MyItemSubOptions
{
  public int ID {get; set;}
  public string SubOptionName {get; set;}
}

Java Script 代码调用 Controller 动作方法来渲染局部视图和提交局部视图

$.ajax({
    url: '/MyController/MyItemsPartialView',
    contentType: 'application/html ; charset:utf-8',
    type: 'GET',
    data: {
        Id: data
    },
    dataType: 'html'
}).done(function (result) {
    //result of MyItemsPartialView action method is displayed in partial view
});

$.post('/MyController/SaveMyItems', $(this).serialize(), function (response) {
    
    //response of SaveMyItems action method is displayed on main view
});
@model ItemsEntryModel

<div class="row">
    <div class="form-group col-lg-12 mb-4">
        <div class="col-lg-12">
            @Model.Item.ItemName
        </div>
        <table class="table table-condensed table-hover bg-inverse-warning">
            <tr>
                @foreach (var item in Model.MyItemsOptionList)
                {
                    <td>
                        @Html.DisplayFor(modelItem => item.OptionName)
                    </td>
                }
            </tr>
            <tr>
                @foreach (var item in Model.MyItemsOptionList)
                {
                    <td>
                        @Html.DropDownListFor(modelItem => item.SelectedItemSubOption, new SelectList(item.MyItemSubOptionsList, "ID", "Name"), new { @id = "Product_" + item.MyItemOptionUniqueNo, @class = "form-control" })
                        <input id="lblMyItemOptionUniqueNo" type="hidden" value="@Html.DisplayFor(modelItem => item.MyItemOptionUniqueNo)" />
                    </td>
                }
            </tr>
        </table>
    </div>
</div>

标签: c#htmlasp.net-mvc

解决方案


推荐阅读