【问题标题】:Posting selected checkboxes to controller action with viewModel使用 viewModel 将选定的复选框发布到控制器操作
【发布时间】:2013-07-01 10:13:33
【问题描述】:

对于现有的基于 MVC 的应用程序,有一个 Product 视图,其 ViewModel 为 ProductViewModel,该 ViewModel 具有 Product 可以具有的所有基本属性,如产品名称、类型、价格等......

使用此视图上的产品创建过程,目标是将客户列表与产品相关联(这不是强制性的)。

要检索客户列表以供用户选择那些关联的客户,目前在单击按钮时,有 ajax 调用 (getCustomers) 请求控制器操作以获取列表并将其与复选框一起显示在表格中,此 html 创建于jQuery Ajax 调用中的苍蝇,

在当前实现中,在对产品视图进行 POST 操作时,选定的 ID 不会填充到视图模型中。

目标是将选定的客户 ID 以及产品详细信息放入 ViewModel。

有什么办法吗?

【问题讨论】:

  • 你能贴一些代码吗?
  • @JeevanJose,问题的哪一部分不清楚?我的意思是,如果问题不清楚,使用代码复制此代码将涉及许多要在此处发布的代码,如果您提出解决问题的设计建议,我们将不胜感激。
  • 我说的是你有复选框的代码。只有看它,我们才能知道出了什么问题。如果你根本不知道怎么做,那么我可以编一些代码告诉你。
  • 使用 ajax 调用客户列表和以下成功方法 (jQuery) , function getCustomersResponse(){ // html on the fly $('div#customersArea').prepend('<table id="customers"><thead class="TableHeader"></thead><tbody></tbody></table>'); <br/> $.each(data, function (index, tdData) { <br/> $('#customers tbody').prepend('<tr><td><input id=CustomerId' + tdData.Id + ' type=checkbox value="' + tdData.Id + '" name="CustomerIds"/></td><td>' + tdData.Name + '</td><td>' + tdData.Type + '</td><td>' + tdData.ActiveFrom + '</td><td>' + tdData.TermsAndCondition + '</td></tr>'); } }
  • @JeevanJose,上面的代码(格式很差)显示了 jquery 函数,用于成功地对客户列表进行 ajax 响应,并且它正在视图中创建,其中我已经删除了不必要的代码。

标签: jquery asp.net-mvc-2


【解决方案1】:

我会尽量以我能理解的最好方式来回答。因此,假设您创建了带有复选框的“表格”,我想它看起来像这样:

<form>
<table>
  <tr><td><input type='checkbox' value='1' name='myCheckbox' />Some text</td></tr>
  <tr><td><input type='checkbox' value='2' name='myCheckbox' />Some text</td></tr>
  <tr><td><input type='checkbox' value='3' name='myCheckbox' />Some text</td></tr>
  <tr><td><input type='checkbox' value='4' name='myCheckbox' />Some text</td></tr>
</table>
<input type="submit" />
</form>

在您的 ProductModel 类中:

public class ProductModel
{
   // Define the property here.
   public int[] MyCheckbox { get; set; }

   // The constructor where you do the initialization
   public void ProductModel(int[] myCheckbox)
   {
      MyCheckbox = myCheckbox;
   }
}

在你的控制器方法中:

[HttpPost]
public ActionResult SomeMethod(ProductModel productModel)
{
    foreach(int value in productModel.MyCheckbox)
    {
        // Your code here..
    }
}

您将在控制器方法中以数组形式获取复选框的值。

【讨论】:

  • 这个例子几乎可以理解确切的问题,[1] 用于复选框创建的 html 在 javascript 函数内 [2] 所有选定的复选框值都需要与产品数据一起在 viewmodel 内,即产品视图模型
  • @Jay 那么,您想将数据从视图发送到模型吗?
  • 在我的 ProductViewModel 中考虑,我有以下属性 public class ProductViewModel { public IEnumerable&lt;string&gt; SelectedCustomerId { get; set; } // &amp; Other Product related properties... } 现在目标是:[HttpPost] public ActionResult Product(ProductViewModel productModel) { // Access selected customers list here }
  • 是的,我想将选定的 customerIds 数据从动态创建的视图发送到带有模型的 ControllerAction。
  • 我们需要考虑这个复选框 html 从 javascript 函数中注入到视图中。
猜你喜欢
  • 2014-09-22
  • 1970-01-01
  • 1970-01-01
  • 2016-11-02
  • 2012-05-28
  • 2015-07-30
  • 1970-01-01
  • 1970-01-01
  • 2014-03-20
相关资源
最近更新 更多