包含Multi Select Dropdown的表单是否未将表单数据提交给服务器?

时间:2019-01-23 12:36:59

标签: c# asp.net-mvc

我必须包含一个简单的表格。

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

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

我已经为此创建了一个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>

ViewModel:

public class CustomerIdAndCategoriesIdsViewModel
{
   public int CustomerId { get; set; }
   public int[] CategoriesIds { get; set; }
}

操作方法。

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

// without ViewModel.
[AllowAnonymous]
public ActionResult Create(int CustomerId, int[] categoryIds)
{
   return View();
}
  

在两种方法中,方法参数的数据均为空。

如何解决?我将非常感谢

2 个答案:

答案 0 :(得分:1)

您的表单元素名称为CustomersCategory。但是您的型号名称不同:

public class CustomerIdAndCategoriesIdsViewModel
{
   public int CustomerId { get; set; }
   public int[] CategoriesIds { get; set; }
}

这意味着您使用的模型呈现页面的方式与接收结果表单发布所使用的模型不同。虽然这并不是天生无效的,但名称​​ do 必须匹配。当模型绑定器收到名为CustomersCategory的属性时,它无法知道如何将它们映射到其他模型。

更新您的模型属性名称:

public class CustomerIdAndCategoriesIdsViewModel
{
   public int Customers { get; set; }
   public int[] Category { get; set; }
}

您可能不愿意这样做,因为现在属性的复数是不正确的。这意味着您的命名会误导某个地方。因此,请在两个模型中更正该命名。

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

答案 1 :(得分:0)

如下更新您的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();
}