Как обновить вторичную таблицу в MVC5 / C # - PullRequest
0 голосов
/ 20 мая 2019

У меня есть представление редактирования в MVC 5, основанное на моей таблице транзакций (ICS_Transactions). Это работает из коробки и никаких проблем.

Мои таблицы нормализованы, и поэтому таблица ICS_Transactions содержит только уникальный идентификатор фактического запаса. В представлении «Правка» обновляется таблица ICS_Transactions, но мне также необходимо обновить ICS_Supplies, чтобы уменьшить объем имеющихся запасов при обработке заказа.

MVC5 и C # очень новы для меня. Я пришел из старых форм asp.net и VB.net, где я просто написал бы свое заявление об обновлении sql и выполнил его.

Мой первый вопрос. , где я это делаю? Должно ли это быть выполнено в действии контроллера [HttpPost] для представления редактирования? Или добавление события onclick для Jscript / jQuery (они также очень новы для меня, и я не очень хорошо знаю, как бы это сделать, но могу искать в Интернете). Мое первоначальное исследование предполагает, что это должно быть сделано в Ajax? Но . , , мой отдел не является поклонником Ajax и хотел бы избежать этого, если это возможно. Не знаю почему.

Вот код для моего редактора

@model ICS20web.Models.ICS_Transactions

<style>
.pos {
    color: black;
    font-weight: normal;
}

.neg {
    color: red;
    font-weight: bold;
}
</style>



@{
ViewBag.Title = "Edit";
}


@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>ICS:  Process Order</h4>




    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.TransID)

    @ViewBag.MyUnit &nbsp; &nbsp; @ViewBag.MyBuilding &nbsp; &nbsp;   @ViewBag.MyStreet &nbsp; &nbsp; @ViewBag.MyCity &nbsp; &nbsp; @ViewBag.MyState &nbsp; &nbsp; @ViewBag.MyZip &nbsp; &nbsp; @ViewBag.MyContact &nbsp; &nbsp; @ViewBag.MyPhone

    <hr />

    <h5><b>Order Details:  @ViewBag.Description</b></h5>

    <!-- Begin Drop Down For Current Order Status-->
    <div class="form-group">
        @Html.Label("Update Current Order Progress:", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="form-control">
                <select name="CheckStatus" id="CheckStatus">

                    <option value=@ViewBag.MyStatus>@ViewBag.MyStatus</option>
                    <option value="Cancelled">Cancelled</option>
                    <option value="Processing">Processing</option>
                    <option value="On Hold">On Hold</option>
                    <option value="Complete">Complete</option>
                    <option value="Low Stock Backordered">Low Stock Backordered</option>
                    <option value="Order Processed">Order Placed</option>

                </select>
            </div>
        </div>
    </div>

    <hr />

    <!-- End Drop Down For Order Current Status-->

    <!-- Begin Drop Down For Open/Closed-->
    <div class="form-group">
        @Html.Label("Close Order:", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="form-control">
                <select name="CheckOpen" id="CheckOpen">

                    <option value="Open">Open</option>
                    <option value="Closed">Closed</option>


                </select>
            </div>
        </div>
    </div>

    <hr />
    <!-- End Drop Down For Open/Closed-->


    <!-- Begin Comments Area-->
    <div class="form-group">
        @Html.LabelFor(model => model.Comments, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextAreaFor(model => model.Comments, 5, 100, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Comments, "", new { @class = "text-danger" })
        </div>
    </div>
    <!-- End Comments Area-->




    <div class="form-group">
        @Html.LabelFor(model => model.UnitsOrdered, (string)"Units On Hand ", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">              
            @Html.TextBox("OnHand", null, new { @class = "form-control", Value = ViewBag.Stock, @readonly = "readonly" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UnitsOrdered, (string)"Number of Units Ordered", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UnitsOrdered, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
            @ViewBag.MyCountIntro @ViewBag.MyCount
            @Html.ValidationMessageFor(model => model.UnitsOrdered, "", new { @class = "text-danger" })

        </div>
    </div>


    <div class="form-group">
        @Html.LabelFor(model => model.UnitsOrdered, (string)"Units Remaining ", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBox("Remaining", null, new { @class = "form-control", Value = ViewBag.Total, @readonly = "readonly" })
        </div>
    </div>




            <div class="form-group">
                @Html.LabelFor(model => model.OriginalDate, (string)"Original Order Date", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.OriginalDate, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
                    @Html.ValidationMessageFor(model => model.OriginalDate, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.TransType, (string)"Transaction Type", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.TransType, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
                    @Html.ValidationMessageFor(model => model.TransType, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.LastUpdatedBy, (string)"Last Updated By", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.LastUpdatedBy, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly", Value = ViewBag.ThisUser } })
                    @Html.ValidationMessageFor(model => model.LastUpdatedBy, "", new { @class = "text-danger" })
                </div>
            </div>



            <div class="form-group">
                @Html.LabelFor(model => model.OpenClosed, (string)"Open / Closed", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.OpenClosed, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
                    @Html.ValidationMessageFor(model => model.OpenClosed, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.CurrentStatus, (string)"Current Status", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.CurrentStatus, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
                    @Html.ValidationMessageFor(model => model.CurrentStatus, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.CurrentStatusDate, (string)"Current Status Date", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.CurrentStatusDate, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
                    @Html.ValidationMessageFor(model => model.CurrentStatusDate, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.RequsitionNumber, (string)"Requisition Number", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.RequsitionNumber, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
                    @Html.ValidationMessageFor(model => model.RequsitionNumber, "", new { @class = "text-danger" })
                </div>
            </div>


            <div class="form-group">
                @Html.LabelFor(model => model.DeliveryMonth, (string)"Expected Delivery Month", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.DeliveryMonth, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
                    @Html.ValidationMessageFor(model => model.DeliveryMonth, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.DeliveryYear, (string)"Expected Delivery Year", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.DeliveryYear, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
                    @Html.ValidationMessageFor(model => model.DeliveryYear, "", new { @class = "text-danger" })
                </div>
            </div>


            <div class="form-group">
                @Html.LabelFor(model => model.Emergency, (string)"Order Is Emergency", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Emergency, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
                    @Html.ValidationMessageFor(model => model.Emergency, "", new { @class = "text-danger" })
                </div>
            </div>


            <div class="form-group" >
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Save" class="btn btn-default" onclick="myFunction();" />
                </div>
            </div>

    <!-- Begin Hidden Fields-->
    <div class="form-group">

        <div class="col-md-10">
            @Html.HiddenFor(model => model.SuppliesID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
            @Html.ValidationMessageFor(model => model.SuppliesID, "", new { @class = "text-danger" })
        </div>
    </div>

      <div class="form-group">

        <div class="col-md-10">
            @Html.Hidden("OrigStock", null, new { @class = "form-control", Value = ViewBag.Stock, @hidden = "hidden" })
        </div>
    </div>

    <div class="form-group">

        <div class="col-md-10">
            @Html.HiddenFor(model => model.Contact, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
            @Html.ValidationMessageFor(model => model.Contact, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">

        <div class="col-md-10">
            @Html.HiddenFor(model => model.DeliveryUnitID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
            @Html.ValidationMessageFor(model => model.DeliveryUnitID, "", new { @class = "text-danger" })
        </div>
    </div>





    <!-- End Hidden Fields-->
        </div>
        }

        <div>
            @Html.ActionLink("Back to List", "Index")
        </div>


        <!-- Add Java Script-->

        @Scripts.Render("~/Scripts/jquery-1.10.2.min.js")
        @Scripts.Render("~/Scripts/CheckContacts.js")
        @Scripts.Render("~/Scripts/Supplies.js")
        @Scripts.Render("~/Scripts/ProcessOrder.js")

Я добавил немного Jscript, который обновляет Элемент "OnHand" до количества запасов в наличии после обработки заказа. И что я пытаюсь сделать, это взять значение «onhand» и обновить таблицу ICS_Supplies следующим образом

Обновление ICS_Supplies Set OnHand = Значение элемента OnHand Где Supplies_ID = Значение элемента SuppliesID

Вот мой HttpPost для представления редактирования. , ,

 // POST: OrderManagement/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "TransID,SuppliesID,OriginalDate,TransType,LastUpdatedBy,Contact,OpenClosed,CurrentStatus,CurrentStatusDate,RequsitionNumber,PONumber,DeliveryMonth,DeliveryYear,UnitsOrdered,Emergency,Comments,DeliveryUnitID")] ICS_Transactions iCS_Transactions)
    {


        if (ModelState.IsValid)
        {
            db.Entry(iCS_Transactions).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(iCS_Transactions);
    }

1 Ответ

0 голосов
/ 20 мая 2019

С помощью предоставленных учебных пособий и некоторых других способов поиска в Интернете я смог решить эту проблему следующим образом:

В основном добавлено небольшое количество кода для поиска в таблице ICS_Supplies, где Suppies_ID = SuppliesID в таблице транзакций и обновление

Спасибо за помощь!

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "TransID,SuppliesID,OriginalDate,TransType,LastUpdatedBy,Contact,OpenClosed,CurrentStatus,CurrentStatusDate,RequsitionNumber,PONumber,DeliveryMonth,DeliveryYear,UnitsOrdered,Emergency,Comments,DeliveryUnitID")] ICS_Transactions iCS_Transactions)
    {
        if (ModelState.IsValid)
        {
            //lookup ICS_Supplies
            var supplyEntity = db.ICS_Supplies.Where(s => s.Supplies_ID == iCS_Transactions.SuppliesID).FirstOrDefault();
            if (supplyEntity != null)
            {
                supplyEntity.OnHand = supplyEntity.OnHand - iCS_Transactions.UnitsOrdered;
            }
            db.Entry(iCS_Transactions).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(iCS_Transactions);
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...