如何在控制器中传递模型的值?

时间:2019-10-22 13:24:00

标签: c# asp.net-mvc

我将尝试将模型的值传递给控制器​​。但是当使用断点进行错误检查时,实际使用的模型为null。我认为我的ajax存在问题,可能会影响它。

我在代码中的主要目的是当我在表示例3行中添加数据时,它可以插入或循环3次。因此在我的数据库中,我有3条记录,但跟踪号不同。跟踪号字段由用户提供,不会自动生成。我被困在这里,请帮忙,谢谢。

我尝试了我所知道的一切,但是没有用。我是新手。

请参阅下面的图片作为参考。

我的控制器

 public ActionResult Add(OrderFormModel model, string[] tracking, string[] deposit)
    {

        //if (model.Quantity <= 0)
        //    ModelState.AddModelError("CustomError", "Quantity must be greater than 0.");

        if (ModelState.IsValid)
        {
            try
            {
                if (model.Id > 0)
                {
                    var order = _orderService.Get(model.Id);

                    order.ClientId = model.ClientId;
                    order.StateId = model.StateId;
                    order.CityId = model.CityId;
                    order.TownId = model.TownId;
                    order.Postcode = model.Postcode;
                    order.Address = model.Address;
                    order.DeliveryDate = Convert.ToDateTime(model.DeliveryDate);
                    //order.Quantity = model.Quantity;
                    order.Deposit = model.Deposit;
                    order.DateDelivered = null;
                    order.Notes = model.Notes;
                    order.DatePosted = Convert.ToDateTime(model.DatePosted);
                    order.DriverId = model.DriverId;

                    if (order.Status == "Delivered" && model.Status == "Cancelled")
                    {
                        ModelState.AddModelError("CustomError", "'Delivered' order cannot be cancelled.");
                        return View(PrepareOrderFormModel(model));
                    }

                    if (model.Status == "Delivered" && model.DateDelivered == null)
                    {
                        ModelState.AddModelError("CustomError", "Date Delivered is required.");
                        return View(PrepareOrderFormModel(model));
                    }

                    if (model.Status == "Delivered")
                    {
                        try
                        {
                            var getUserInrole = _userInRoleService.GetRoleByUserId(order.Client.UserId).RoleId;

                            if ((getUserInrole == 5) || (getUserInrole == 2))
                            {
                                var transaction = new Transaction
                                {
                                    Source = "Order",
                                    TransactionId = order.Id,
                                    Amount = (5 * order.Quantity) - order.Deposit, // TODO: create pricing table.
                                    DateCreated = DateTime.Now,
                                    CreatedBy = User.Identity.Name,
                                    ReferenceNumber = order.ReferenceNumber
                                };
                                _transactionService.Add(transaction);
                            }
                            if (getUserInrole == 3)
                            {
                                var transaction = new Transaction
                                {
                                    Source = "Order",
                                    TransactionId = order.Id,
                                    Amount = (10 * order.Quantity) - order.Deposit, // TODO: create pricing table.
                                    DateCreated = DateTime.Now,
                                    CreatedBy = User.Identity.Name,
                                    ReferenceNumber = order.ReferenceNumber
                                };
                                _transactionService.Add(transaction);
                            }
                        }
                        catch (Exception ex)
                        {
                            ModelState.AddModelError("CustomError", ex.Message);
                            return View(PrepareOrderFormModel(model));
                        }
                    }

                    if (model.Status == "Delivered")
                        //order.DateDelivered = DateTime.Now.Date;
                        order.DateDelivered = model.DateDelivered;

                    order.Status = model.Status;

                    _orderService.Update(order);
                    return RedirectToAction("index");
                }
                else
                {
                    //var serializeData = JsonConvert.DeserializeObject<List<OrderFormModel>>(getepassdata);
                    for (int i = 0; i < tracking.Length; i++)
                    {
                        var getMaxId = _orderService.GetAll().OrderByDescending(x => x.Id).FirstOrDefault();

                        var order = new Order
                        {
                            ClientId = model.ClientId,
                            StateId = model.StateId,
                            CityId = model.CityId,
                            TownId = model.TownId,
                            Postcode = model.Postcode,
                            Deposit = Convert.ToDecimal(deposit[i]),
                            TrackingNumber = tracking[i],
                            Address = model.Address,
                            DatePosted = Convert.ToDateTime(model.DatePosted),
                            DeliveryDate = Convert.ToDateTime(model.DeliveryDate),
                            Quantity = 1,
                            Status = "Lined-up",
                            DateDelivered = null,
                            Notes = model.Notes ?? "",
                        };

                        if (getMaxId != null)
                        {
                            order.ReferenceNumber = "ODR" + Convert.ToString(string.Format("{0:00000}", getMaxId.Id + 1));
                        }
                        _orderService.Add(order);
                    }
                    return RedirectToAction("add");
                }
            }

            catch (Exception ex)
            {
                ModelState.AddModelError("CustomError", ex.InnerException.Message);
            }
        }

        model = PrepareOrderFormModel(model);
        return View(model);
    }

我的脚本

$(".btnAdd").click(function () {
    var tracking = '<td>@Html.TextBoxFor(x => x.TrackingNumber, new { @class = "form-control tracking" })</td>';
    var deposit = '<td>@Html.TextBoxFor(x => x.Deposit, new { @class = "form-control deposit" })</td>';
    $("tbody").append('<tr>' + tracking + deposit + '</tr>');
});

function getAllData() {
    var data = [];
    $('tbody tr').each(function () {
        var TrackingNumber = $(this).find('.tracking').val();
        var Deposit = $(this).find('.deposit').val();

        var alldata = {
            'TrackingNumber': TrackingNumber,
            'Deposit': Deposit,
        }
        data.push(alldata);
    });
    console.log(data);
    return data;
}


$('#btnSubmit').click(function () {
    var data = JSON.stringify(getAllData());
    $.ajax({
        url: '@Url.Action("add", "order")',
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ 'getepassdata': data }),
        success: function () {
            alert("Data Added Successfully");
        },
        error: function () {
            alert("Error while inserting data");
        }
    });
});

查看

@using (Html.BeginForm("add", "order", FormMethod.Post)){
@Html.HiddenFor(x => x.Id)
@Html.Raw(TempData["msg"])

<div class="ContainerBanner">
    @Html.Partial("_Message")
    <h3 class="orders">Order</h3><br />
    <div class="row">
        <div class="col-md-4">
            <div class="form-group">
                @Html.LabelFor(x => x.ClientId, new { @class = "form-label label-color" })
                @Html.DropDownListFor(x => x.ClientId, Model.Clients, "", new { @class = "form-control", @id = "s-clients" })
            </div>
        </div>

        <div class="col-md-2">
            <div class="form-group">
                @Html.LabelFor(x => x.Postcode, new { @class = "form-label" })
                @Html.TextBoxFor(x => x.Postcode, new { @class = "form-control" })
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-2">
            <div class="form-group">
                @Html.LabelFor(x => x.StateId, new { @class = "form-label label-color" })
                @Html.DropDownListFor(x => x.StateId, Model.States, new { @class = "form-control", @id = "s-states" })
            </div>
        </div>

        <div class="col-md-2">
            <div class="form-group">
                @Html.LabelFor(x => x.CityId, new { @class = "form-label label-color" })
                @Html.DropDownListFor(x => x.CityId, Model.Cities, new { @class = "form-control", @id = "s-cities" })
            </div>
        </div>

        <div class="col-md-2">
            <div class="form-group">
                @Html.LabelFor(x => x.TownId, new { @class = "form-label" })
                @Html.DropDownListFor(x => x.TownId, Model.Towns, new { @class = "form-control", @id = "s-towns" })
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-2">
            <div class="form-group">
                @Html.LabelFor(x => x.DatePosted, new { @class = "form-label label-color" })
                <div class='input-group date datetimepicker'>
                    @Html.TextBoxFor(x => x.DatePosted, new { @class = "form-control" })
                    <span class="input-group-addon">
                        <span class="glyphicon glyphicon-calendar"></span>
                    </span>
                </div>
            </div>
        </div>

        <div class="col-md-2">
            <div class="form-group">
                @Html.LabelFor(x => x.DeliveryDate, new { @class = "form-label label-color" })
                <div class='input-group date datetimepicker'>
                    @Html.TextBoxFor(x => x.DeliveryDate, new { @class = "form-control" })
                    <span class="input-group-addon">
                        <span class="glyphicon glyphicon-calendar"></span>
                    </span>
                </div>
            </div>
        </div>

        <div class="col-md-2">
            <div class="form-group">
                @Html.LabelFor(x => x.DateDelivered, new { @class = "form-label" })
                <div class='input-group date datetimepicker'>
                    @Html.TextBoxFor(x => x.DateDelivered, new { @class = "form-control" })
                    <span class="input-group-addon">
                        <span class="glyphicon glyphicon-calendar"></span>
                    </span>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-6">
            <div class="form-group">
                @Html.LabelFor(x => x.Address, new { @class = "form-label label-color" })
                @Html.TextBoxFor(x => x.Address, new { @class = "form-control" })
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-2">
            <div class="form-group">
                @Html.LabelFor(x => x.Status, new { @class = "form-label" })
                <select class="form-control" name="Status" id="ShowHide">
                    <option value="Lined-up" @(Model.Status == "Lined-up" ? "selected" : "")>Lined-up</option>
                    <option value="Confirmed" @(Model.Status == "Confirmed" ? "selected" : "")>Confirmed</option>
                    <option value="Cancelled" @(Model.Status == "Cancelled" ? "selected" : "")>Cancelled</option>
                    <option value="Delivered" @(Model.Status == "Delivered" ? "selected" : "")>Delivered</option>
                </select>
            </div>
        </div>

        <div class="row">
            <div class="col-md-2">
                <div class="form-group">
                    @Html.LabelFor(x => x.DriverId, new { @class = "form-label" })
                    @Html.DropDownListFor(x => x.DriverId, Model.Drivers, "", new { @class = "form-control" })
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-6">
            <table class="table">
                <thead>
                    <tr>
                        <th>
                            @Html.LabelFor(x => x.TrackingNumber, new { @class = "form-label" })
                        </th>
                        <th>
                            @Html.LabelFor(x => x.Deposit, new { @class = "form-label" })
                        </th>
                    </tr>
                </thead>

                <tbody>
                    <tr>
                        <td>
                            @Html.TextBoxFor(x => x.TrackingNumber, new { @class = "form-control tracking" })
                        </td>
                        <td>
                            @Html.TextBoxFor(x => x.Deposit, new { @class = "form-control deposit" })
                        </td>
                    </tr>
                </tbody>

                <tfoot>
                    <tr>
                        <td>
                            <input class="btnAdd btn btn-default" type="button" name="name" value="Add" />
                        </td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>

    <div class="row">
        <div class="col-md-6">
            <div class="form-group">
                @Html.LabelFor(x => x.Notes, new { @class = "form-label" })
                @Html.TextAreaFor(x => x.Notes, new { @class = "form-control" })
            </div>
        </div>
        <div class="col-md-6"></div>
    </div>

    <br />
    <button type="submit" id="btnSubmit" class="btn btn-primary btn-sm"><i class="fas fa-save"></i> &nbsp;Save Order</button>
    <a href="@Url.Action("index", "order")" class="btn btn-default btn-sm"><i class="fa fa-long-arrow-alt-left"></i> &nbsp;Back to list</a>
</div> }

0 个答案:

没有答案