首页 > 解决方案 > How to pass object with input value to controller post method

问题描述

I've created a table of items in a form with buttons next to each for ordering. For each item, I want the user to specify a quantity before submitting. Upon clicking the order button, I need the item, as well as the quantity parameters to be sent to the controller post method, where I'm sending this data to a Sql Server for manipulation (I have stored procedures written in Sql). I'm having trouble figuring out how to send both the ItemId and the InputQty to the controller post method from the view.

//Model

public class USA
    {
        [Key]
        public int ItemId { get; set; }
        public int PlanSeqId { get; set; }
        public string ItemDescription { get; set; }
        public int OrderQuantity { get; set; }
        public int OrderSldTdy { get; set; }
        public int PlannedMinutesQty { get; set; }
        public int ActualMinutesQty { get; set; }
        public int NetworkId { get; set; }
        public int CompanyId { get; set; }
        public int AvaiForSaleQty { get; set; }
        [DataType(DataType.Date)]
        public DateTime ShowDate { get; set; }
        public string ShowCd { get; set; }
        [NotMapped]
        public int InputQty { get; set; } 
    }
}

//Controller

private readonly OrderContext _context;

        public USAsController(OrderContext context)
        {
            _context = context;
        }

        // GET: USAs
        public async Task<IActionResult> Index()
        {
            return View(await _context.USA.ToListAsync());
        }

[HttpPost]
        public IActionResult Order(USA usa)
        {          

            string path = Directory.GetCurrentDirectory();
            var builder = new ConfigurationBuilder()
                .SetBasePath(path)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            IConfiguration config = builder.Build();
            string sqlConnectionString = config.GetConnectionString("OrderContext");
            string sql = "OrderItemUpdate";            

            if (usa.AvaiForSaleQty != 0 && usa.AvaiForSaleQty - usa.OrderQuantity >= 0)
            {
                using (var connection = new SqlConnection(sqlConnectionString))
                {
                    try
                    {
                        connection.Open();
                        DynamicParameters parameter = new DynamicParameters();
                        parameter.Add("@CompanyId", usa.CompanyId, DbType.Int32, ParameterDirection.Input);
                        parameter.Add("@ItemId", usa.ItemId, DbType.Int32, ParameterDirection.Input);
                        parameter.Add("@PlanSeqId", usa.PlanSeqId, DbType.Int32, ParameterDirection.Input);
                        parameter.Add("@ItemDescription", usa.ItemDescription, DbType.String, ParameterDirection.Input);
                        parameter.Add("@OrderQuantity", usa.OrderQuantity, DbType.Int32, ParameterDirection.Input);
                        parameter.Add("@OrderSldTdy", usa.OrderSldTdy, DbType.Int32, ParameterDirection.Input);
                        parameter.Add("@PlannedMinutesQty", usa.PlannedMinutesQty, DbType.Int32, ParameterDirection.Input);
                        parameter.Add("@ActualMinutesQty", usa.ActualMinutesQty, DbType.Int32, ParameterDirection.Input);
                        parameter.Add("@NetworkId", usa.NetworkId, DbType.Int32, ParameterDirection.Input);
                        parameter.Add("@AvaiForSaleQty", usa.AvaiForSaleQty, DbType.Int32, ParameterDirection.Input);
                        parameter.Add("@ShowDate", usa.ShowDate, DbType.String, ParameterDirection.Input);
                        parameter.Add("@ShowCd", usa.ShowCd, DbType.String, ParameterDirection.Input);
                        connection.Execute(sql, parameter, commandType: CommandType.StoredProcedure);
                        return RedirectToAction(nameof(Index));
                    }
                    catch (SqlException ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    connection.Close();
                }
                return View();
            }
            else
            {
                ViewBag.Message("Inventory too low for amount ordered.");
                return View();
            }
        }

//View

@model IEnumerable<QxHOrderSystem.Models.USA>

@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>
<form asp-action="Order" method="post" class="form">
    <table class="table">
        <thead>
            <tr>
                <th></th>
                <th>
                    @Html.DisplayNameFor(model => model.ItemId)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.ItemDescription)
                </th>
                <th>
                    Order Quantity
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.AvaiForSaleQty)
                </th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>                        
                        <input type="submit" value="Order" />                        
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.ItemId)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.ItemDescription)
                    </td>
                    <td>
                        <input asp-for="@item.InputQty" class="form-control" value="" />
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.AvaiForSaleQty)
                    </td>
                    <td>
                        <a asp-action="Edit" asp-route-id="@item.ItemId">Edit</a> |
                        <a asp-action="Details" asp-route-id="@item.ItemId">Details</a> |
                        <a asp-action="Delete" asp-route-id="@item.ItemId">Delete</a>
                    </td>
                </tr>
            }
        </tbody>
    </table>
</form>

Is there a way to do this without using jQuery? I'm not opposed to it, but I feel as if there's a simple way that I'm just not seeing using HTML/C#. Thanks in advance.

标签: c#htmlrazorasp.net-core-mvc

解决方案


That seems you only want to post single entity to server side , you can modify the codes like :

@model List<QxHOrderSystem.Models.USA>
<table class="table">
    <thead>
        <tr>
            <th></th>
            <th>
                ItemId
            </th>
            <th>
                ItemDescription
            </th>
            <th>
                Order Quantity
            </th>
            <th>
                AvaiForSaleQty
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @for (int i = 0; i < Model.Count(); i++)
        {
            using (Html.BeginForm("Order", "Home", FormMethod.Post))
            {
                <tr>
                    <td>
                        <input type="submit" value="Order" />
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => Model[i].ItemId)
                        <input type="hidden" value="@Model[i].ItemId"  name="ItemId"/>
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => Model[i].ItemDescription)
                    </td>
                    <td>
                        @Html.EditorFor(model => Model[i].InputQty, null, "InputQty")
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => Model[i].AvaiForSaleQty)
                    </td>
                    <td>
                        <a asp-action="Edit" asp-route-id="@Model[i].ItemId">Edit</a> |
                        <a asp-action="Details" asp-route-id="@Model[i].ItemId">Details</a> |
                        <a asp-action="Delete" asp-route-id="@Model[i].ItemId">Delete</a>
                    </td>
                </tr>
            }
        }

    </tbody>
</table>

On server side :

public IActionResult Order(USA usa)
{
   .....
}

That will send ItemId and InputQty when clicking the Order button .

But i would suggest using javascript to get the values and sending the values to server side using Ajax .


推荐阅读