C# 包含多选下拉列表的表单是否未向服务器提交表单数据?

C# 包含多选下拉列表的表单是否未向服务器提交表单数据?,c#,asp.net-mvc,C#,Asp.net Mvc,我必须使用包含的简单表单 第一个字段:具有单一选择模式的下拉列表 第二个字段:具有多选模式的下拉列表 我已经为此创建了一个viewModel,当我们将表单提交到服务器时,viewMode将使用MVC模型绑定接收数据,但不幸的是它无法工作 表格编号: <h2><strong>New Customer Details Record</strong></h2> <form action="~/CustomerCategoryRecorder/Cre

我必须使用包含的简单表单

第一个字段:具有单一选择模式的下拉列表

第二个字段:具有多选模式的下拉列表

我已经为此创建了一个viewModel,当我们将表单提交到服务器时,viewMode将使用MVC模型绑定接收数据,但不幸的是它无法工作

表格编号:

<h2><strong>New Customer Details Record</strong></h2>
<form action="~/CustomerCategoryRecorder/Create" method="post">
    <div class="form-group">
        <label>Customer</label>
        @Html.DropDownListFor(m => m.Customers, new SelectList(Model.Customers, "id", "name"), "Select Customer", new { @class = "form-control" })
    </div>

    <div class="form-group">
        <label>Category</label>
        @Html.DropDownListFor(m => m.Category, new MultiSelectList(Model.Categories, "id", "name"), "Select Customers Categories", new { multiple = "true", @class = "form-control"})
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>
行动方法

// Using ViewModel.
[AllowAnonymous]
public ActionResult Create(CustomerIdAndMoviesIdsViewModel ids)
{
   return View();
}

// without ViewModel.
[AllowAnonymous]
public ActionResult Create(int CustomerId, int[] categoryIds)
{
   return View();
}
在动作方法的两种情况下,方法参数的数据都为null


如何解决?我将非常感谢

更新您的ViewModel,如下所示

public class CustomerIdAndCategoriesIdsViewModel
{
   public int Customers { get; set; }
   public int[] Category { get; set; }
}
添加操作
Create
和添加
[HttpPost]
注释

[AllowAnonymous]
[HttpPost]
public ActionResult Create(CustomerIdAndMoviesIdsViewModel ids)
{
   return View();
}

您的表单元素名称是
客户
类别
。但您的型号名称不同:

public class CustomerIdAndCategoriesIdsViewModel
{
   public int CustomerId { get; set; }
   public int[] CategoriesIds { get; set; }
}
这意味着您使用不同的模型来呈现页面,而不是接收生成的表单帖子。虽然这并非天生无效,但名称确实需要匹配。当模型绑定器收到名为
客户
类别
的属性时,它无法知道如何将它们映射到其他模型

更新模型特性名称:

public class CustomerIdAndCategoriesIdsViewModel
{
   public int Customers { get; set; }
   public int[] Category { get; set; }
}
您可能不愿意这样做,因为现在属性的多元化是不正确的。这意味着你的名字有误导性。因此,在两种模型中都要更正该命名


基本上,无论表单元素名称是什么,模型属性名称都是如此。这就是模型绑定器将发布的值映射到模型属性的方式。

在您的视图中,模型属性称为
客户
类别
,但在您的模型中它们不是?听起来您使用的是具有不同属性名称的不同模型。这些方法是否经过修饰以允许post?您的表单操作是
~/CustomerCategoryRecorder/Create
,但您没有任何名为
Create
的操作。此外,您应该将class
customeriandcategoriesidsviewmodel
属性更新为
Customers
Category
。将[post]属性放入第二个创建中method@David对我正在呈现表单数据,其中包括有关客户和类别的数据。因此,这与我提交的viewModel不同。
public class CustomerIdAndCategoriesIdsViewModel
{
   public int Customers { get; set; }
   public int[] Category { get; set; }
}