如何使用json从html表发布数据到ASP.NET MVC中的控制器

时间:2013-04-19 06:15:02

标签: jquery asp.net-mvc

我的视图包含salesmainsalesub详细信息

@using (Html.BeginForm())
{
<TABLE >
<tr>
<td>
<label id="lblBuyerName" style="color: white">BuyerName</label>
</td>
<td>
<input type="text" name="txtBuyerName" id="BuyerName" style="width: 250px;"/>
</td>

</tr>
<tr>
<td>
<label id="lblDate">Date</label>
</td>
<td>
<input type="text" name="txtDate" id="tDate" style="width: 100px; height: 15px;" />
</td>

</tr>

</TABLE>

<div style="background-color: lightsteelblue; min-height: 125px; min-width: 50px; border-bottom: ActiveBorder; padding-right: 500px;">
<TABLE id="dataTable" border="3" style="padding-left: 49px; margin-left: 10px;">
<tr>
<td>
SELECT
</td>
<td>
REGION
</td>
<td>
QUANTITY
</td>
<td>
RATE
</td>
<td>
AMOUNT
</td>
<td>
TAX PERCENTAGE
</td>
<td>
TAX AMOUNT
</td>


</tr>
<TR>
<TD><INPUT type="checkbox" name="chk"/></TD>
<TD> @Html.DropDownList("country", new SelectList(ViewBag.ListOfDisciplines, "Value", "Text", Model)) </TD>
<TD> <INPUT type="text" name="Quantity" id="Quantity"/> </TD>
<td>
<input type="text" name="Rate" id="Rate" />
</td>
<td>
<input type="text" name="Amount" id="Amount" style="width: 100px; color: green" readonly="true"/>
</td>
<td>
<input type="text" name="TaxPer" id="TaxPer" style="width: 100px; color: green" readonly="true"/>
</td>
<td>
<input type="text" name="TaxAmt" id="TaxAmt" style="width: 100px; color: green" readonly="true"/>
</td>
</TR>
</TABLE>
<input type="button" value="Add Row" onclick=" addRow('dataTable') " style="border-left-width: 1px; margin-left: 10px;"/>
<input type="button" value="Delete Row" onclick=" deleteRow('dataTable') " />
<br />
<div style="font: italic small-caps bold 20px georgia, garamond, serif;">
<table >
<tr>
<td style="margin-left: 1px; padding-left: 1px;">Grand_Total:</td>
<td><input type="text" readonly="true" name="grand_total" id="grand_total" style="width: 100px; color: green"/></td>
<td>All_Tax:</td><td> <input type="text" readonly="true" name="All_totalTax" id="All_totalTax" style="width: 100px; color: green" /></td>
<td>All_Total:</td><td> <input type="text" name="All_total" readonly="true" id="All_total" style="width: 100px; color: green" /></td>
</tr>
</table>
</div>
</div>
<div>
<input type="submit" id="btnSaveALL" value="Save Record" style="border-left-width: 1px; margin-left: 10px;"/>
</div>
}

我的Ajax功能是

<script language="javascript" type="text/javascript">
          $(document).ready(function () {
                    $(function () {
                        $("#tDate ").datepicker();
                    });

                    $("#btnSaveALL").click(function () {

                        $.ajax({
                            type: "POST",
                            url: "Sales/ShowTable",
                            success: function (response) {
                                alert('Document Saved.');
                            }
                        });
                    });
                });
    </script>

,控制器操作方法是:

[HttpPost]
public ActionResult ShowTable()
{
    return View();
}

txtBuyerNametxtDategrand_totalAll_totalAll_totalTax列都属于salesmain类。

countryQuantityRateAmountTaxPerTaxAmt列都属于salessubs类< / p>

我想使用jQuery json将所有数据发布到控制器。那么jQuery的ajax函数和控制器方法代码应该是什么?

提前谢谢你......

1 个答案:

答案 0 :(得分:0)

您可以先编写一个代表您要提交的数据的视图模型(您可能需要根据具体要求调整各种属性的数据类型):

public class SalesViewModel
{
    public string Country { get; set; }
    public int Quantity { get; set; }
    public decimal Rate { get; set; }
    public int Amount { get; set; }
    public decimal TaxPer { get; set; }
    public decimal TaxAmt { get; set; }
}

public class MyViewModel
{
    public string BuyerName { get; set; }
    public DateTime Date { get; set; }
    public decimal AllTotal { get; set; }
    public decimal AllTotalTax { get; set; }
    public SalesViewModel[] Sales { get; set; }
}

然后:

<script type="text/javascript">
    $(function () {
        $('#tDate').datepicker();

        $('form').submit(function () {
            var sales = [];
            $('#dataTable tr').each(function() {
                sales.push({
                    country: $('td select', this).val(),
                    quantity: $('td input[name="Quantity"]', this).val(),
                    rate: $('td input[name="Rate"]', this).val(),
                    amount: $('td input[name="Amount"]', this).val(),
                    taxPer: $('td input[name="TaxPer"]', this).val(),
                    taxAmt: $('td input[name="TaxAmt"]', this).val(),
                });
            });
            var model = { 
                buyerName: $('#BuyerName').val(),
                date: $('#tDate').val(),
                allTotal: $('#All_total').val(),
                allTotalTax: $('#All_totalTax').val(),
                sales: sales
            };
            $.ajax({
                url: this.action,
                type: this.method,
                contentType: 'application/json',
                data: model,
                success: function (response) {
                    alert('Document Saved.');
                }
            });

            return false;
        });
    });
</script>

现在您的控制器操作可以将视图模型作为参数:

[HttpPost]
public ActionResult ShowTable(MyViewModel model)
{
    ...
}

据说你的HTML很糟糕。您有重复的ID,这是不允许的。另外一个改进步骤是将此视图模型用作视图的模型,并使用强类型帮助程序(如Html.EditorFor)生成输入字段,而不是像您一样对其进行硬编码。这将允许您大大简化AJAX调用,因为您不再需要在输入字段的名称和视图模型的属性名称之间进行映射。默认的模型绑定器将能够按约定绑定它们:

<script type="text/javascript">
    $(function () {
        $('#tDate').datepicker();

        $('form').submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (response) {
                    alert('Document Saved.');
                }
            });

            return false;
        });
    });
</script>