ASP.MVC - 通过使用表单如何将参数传递给Controller?

时间:2017-01-03 00:54:15

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我已将表单添加到我的默认索引视图中,并为名为“数量”的Html.TextBox添加了一列。当我点击提交时,我将其发送到Action“OrderForm”,但是当我调试时,我只传递数量值和 itemName inventory_no 为空。有人可以帮忙吗?

enter image description here

以下是我的MVC的示例代码:

型号:

[Table("inventory")]
public partial class inventory
{
    [Key]
    [Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int inventory_no { get; set; }

    public string name { get; set; }
}    

查看:

 @model IEnumerable<MYAPP.inventory>
@{
ViewBag.Title = "Index";
}
@using (Html.BeginForm("orderForm", "inventories", FormMethod.Post))
{
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>

<div id="details"></div>
<table class="table">
<tr>
    <th>
        Quantity
    </th>
    <th>
        Name
    </th>
</tr>

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.TextBox("Quantity",0, new { style = "width:30px",       
 @class = "selectedItem"})
        </td>
        <td class="itemName"><b>
@Html.DisplayFor(modemItem => item.name)
</b>
        </td>
        <td>
            <a href="#" class="remove" data-url="@Url.Action("Remove", new { id = item.inventory_no })">Remove</a>
            @Html.ActionLink("Edit", "Edit", new { inventory_no = item.inventory_no.ToString(), client_no = item.client_no }) |
            @Html.ActionLink("Delete", "Delete", new { inventory_no = item.inventory_no.ToString(), client_no = item.client_no })
        </td>
    </tr>
}
</table>
<input type="submit" value="Submit your order" />
}

控制器:

  public ViewResult orderForm (int quantity, string itemName, int? inventory_no)
    {

        return View();
    }

1 个答案:

答案 0 :(得分:1)

您当前的代码仅为数量生成标记。如果您需要inventory_id和name值,则需要具有表单字段。

您可以将这些值保存在隐藏字段中,其名称与您的操作方法参数匹配。此外,由于您的操作方法需要一个库存项目详细信息,您应该为循环中的每个项目提供表单和提交按钮

@foreach (var item in Model)
{
   using(Html.BeginFor("orderForm","YourcontrollerName"))
   {
    <tr>
        <td>
            @Html.TextBox("Quantity",0, new { @class = "selectedItem"})
        </td>
        <td class="itemName"> @Html.DisplayFor(modemItem => item.name) 
                              @Html.Hidden("name",item.name)
                              @Html.Hidden("inventory_no",item.inventory_no)

        </td>
        <td>
            <input type="submit" value="Submit your order" />
             <!-- your existing links here-->
        </td>
    </tr>
  } 
}