Как получить значения из модального окна частичного просмотра для обновления формы?

Я новичок в ASP.NET MVC, и у меня есть модальное окно начальной загрузки, которое обрабатывает одну транзакцию, и я пытаюсь получить значения из модального окна, а затем, когда я нажимаю кнопку добавления, я хочу, чтобы модальное окно закрылось, а затем отправьте сообщение ajax в контроллер. Контроллер должен обрабатывать коллекции и единственный экземпляр объекта, не уверен, что он полностью верен. Я добавил пример ссылки на dotnetfiddle, чтобы упростить обмен кодом.

Можно ли сделать это с помощью модального окна начальной загрузки для лучшего взаимодействия с пользователем?

Чего я пытаюсь достичь: когда вы добавляете транзакцию, нажимая кнопку «Создать транзакцию» при вводе даты и суммы, эти значения должны быть добавлены в коллекцию CustomerTransactions и отображены в форме с указанием текущего количества транзакций и того, что они есть. Я добавил неупорядоченный список в html.

Вот структура данных:

Представление: только одно представление с формой, элементами, html и jQuery и вызовом ajax.

ViewModel:

using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;

namespace HelloWorldMvcApp
{
    public class SampleViewModel
    {
        [Required]
        [MinLength(10)]
        [MaxLength(100)]
        [Display(Name = "Ask Magic 8 Ball any question:")]
        public string Question { get; set; }

        //See here for list of answers
        public string Answer { get; set; }

        //Ignore the above properties for now
        public int Id { get; set; }
        public string Name { get; set; }
        public SampleTransactionItemViewModel CustomerTransaction { get; set; }
        public List<SampleTransactionItemViewModel> CustomerTransactions { get; set; }
    }

    public class SampleTransactionItemViewModel
    {
        public DateTime TransactionDate { get; set; }
        public decimal TransactionAmount { get; set; }
    }
}

Контроллер:

using System;
using System.Web.Mvc;
using System.Collections.Generic;

namespace HelloWorldMvcApp
{
    public class HomeController : Controller
    {
        private static Random _rnd = new Random();  
        private static List<string> _db = new List<string> { 
            "Yes", "No", "Definitely, yes", "I don't know", "Looks like, yes"
        };

        [HttpGet]
        public ActionResult Index()
        {
            return View(new SampleViewModel());
        }


        /*[HttpPost]
        public JsonResult GetAnswer(string question)
        {               
            int index = _rnd.Next(_db.Count);
            var answer = _db[index];
            return Json(answer);
        }*/

        [HttpPost]      
        public ViewResult AddTransactionItem(SampleViewModel model)
        {
            model.CustomerTransactions.Add(model.CustomerTransaction);
            model.CustomerTransaction = null;

            //return PartialView("Modal/TransactionModal", output);
            return View("FraudCheckBankAccountForm", model);
        }
    }
}

Вид

@{
    Layout = null;
}

<!DOCTYPE html>
<!-- template from https://getbootstrap.com/getting-started -->

<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Bootstrap 101 Template</title>

        <!-- CSS Includes -->
        <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

        <style type="text/css">

            .field-validation-error {
                color: #ff0000;
            }
            p{
            padding: 10px 0;
            }

        </style>
    </head>

    <body>
        <div class="container">
            <div class="col-md-6 col-md-offset-3">
                <h4>Example Adding items to collection dynamically</h4><br>

                @using (Html.BeginForm())
                {
                    <div class="form-group">
                        @Html.LabelFor(m => m.Name)
                        @Html.TextBoxFor(model => model.Name, new {@class="form-control"})                      
                    </div>


                        <div class="form-group">
                            <button type="button" class="btn btn-primary"  >
                                Create Transaction
                            </button>
                        </div>

                    <div class="form-group">
                        Current transactions
                        <!-- Added here dynamically-->
                        Transactions:
                        <ul>
                            <li>TransactionDate: Date here</li>
                            <li>TransactionAmount: Amount here</li>
                        </ul>
                    </div>

                       <br>
                       <button type="button" class="btn btn-success submit">Save</button>

                        <div class="modal fade" id="TransactionModal" tabindex="-1" role="dialog" aria-labelledby="TransactionModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close"  aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">Create transaction</h4>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label class="col-md-3 control-label">Date</label>
                    <div class="col-md-9">
                        @Html.TextBoxFor(a => a.CustomerTransaction.TransactionDate, new { @class = "form-control Date", @id = "Transaction_Date", @name = "Transaction.Date", @type ="date" })
                    </div>
                </div>
                <div class="form-group NoBottomPad">
                    <label class="col-md-3 control-label">Amount</label>
                    <div class="col-md-9">
                        @Html.TextBoxFor(a => a.CustomerTransaction.TransactionAmount, new { @class = "form-control Amount", @id = "Transaction_Amount", @name = "Transaction.Amount"})
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <div class="row">
                    <div class="col-md-8">
                        <div class="hinttext" style="font-size: smaller; text-align: left; margin-left: -10px; display: table-cell; vertical-align: bottom; ">
                            Example
                        </div>
                    </div>
                    <div class="col-md-4">
                        <button class="btn" id="TransactionModalCancelButton" name="TransactionModalCancelButton" type="button" >Cancel</button>
                        <button class="btn-default btn" id="AddTransaction" name="AddTransaction" type="button" disabled>Add</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
                }

                <br/><br/>
                <div class="alert alert-warning fade">
                    <img src="https://entechprod.blob.core.windows.net/dotnetfiddle/morpheus.jpg" style="max-width:100%;"/><br/><br/>
                    <strong><span class="alert-content"></span></strong>
                </div>
            </div>
        </div>

        <!-- JS includes -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>

        <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
        <script src="https://ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>

        <script type="text/javascript">

            function openAlert(txt) {
                $('.alert-content').text(txt);
                $('.alert').addClass('in');
            }

            function closeAlert() {
                $('.alert').removeClass('in');
            }

            $(function(){
                var answer = '@Model.Answer';

                if(answer && answer != '') 
                    openAlert(answer);

                $('#Question').change(closeAlert);
                $('#Question').keyup(closeAlert);

                // This is the save button
                var save = document.getElementById("AddTransaction");
                var cancel = document.getElementById("TransactionModalCancelButton");

                // This is the text fields
                var date = document.getElementById("Transaction_Date");
                var amount = document.getElementById("Transaction_Amount");

                // This is the transaction list
                var transList = document.getElementById("CustomerTransactions");
                var container = document.getElementById("TransactionResult");

                // Date validation
                $(date).change(function () {
                    if ($(this).val() !== "" && $(amount).val() !== "") {
                        $(save).prop('disabled', false);
                    } else {
                        $(save).prop('disabled', true);
                    }
                });

                // Amount validation
                $(amount).keyup(function () {
                    if ($(this).val() !== "" && $(date).val() !== "") {
                        $(save).prop('disabled', false);
                    } else {
                        $(save).prop('disabled', true);
                    }
                });

                $('.submit').click(function(){
                    if($('form').valid()) {

                        $.ajax({
                            url: '@Url.RouteUrl(new{ action="GetAnswer", controller="Home"})',
                            data: {Answer: '', Question: $('#Question').val()},
                                type: 'POST',
                                dataType: 'json',
                                contentType: "application/json; charset=utf-8",
                                success: function(resp) {
                                openAlert(resp);
                        }});
                    }
                    else {
                        closeAlert();
                    }
                });

            });

        </script>
    </body>
</html>

Также я хотел бы добавить динамический список в представление, но не знаю, как его реализовать. Просмотрите ссылку на dotnetfiddle ниже для кода.

                    <div class="form-group">
                        Current transactions
                        <!-- Added here dynamically foreach transaction in transactions-->
                        Transactions:
                        <ul>
                            <li>TransactionDate: Date here</li>
                            <li>TransactionAmount: Amount here</li>
                        </ul>
                    </div>
                    <div class="form-group">
                        Current transactions
                        <!-- Added here dynamically-->
                        Transactions:
                        <ul>
                            <li>TransactionDate: Date here</li>
                            <li>TransactionAmount: Amount here</li>
                        </ul>
                    </div>

Ссылка на код: https://dotnetfiddle.net/2uG3sv

См. также:  структура typedef в определении структуры файла заголовка в файле c
Понравилась статья? Поделиться с друзьями:
IT Шеф
Комментарии: 1
  1. nless

    Вы можете использовать JQuery следующим образом:

    1- При нажатии на add вызовите AddTransactionItem с помощью $.port.

    2- Скройте модель, если нет ошибки.

     $('#AddTransaction').click(function () {
            var TransactionDate = $('#Transaction_Date').val();
            var TransactionAmount = $('#Transaction_Amount').val();
    
            $.post('@Url.Action("AddTransactionItem","Home")', { CustomerTransaction: {TransactionDate: TransactionDate, TransactionAmount: TransactionAmount} })
                .done(function (data) {
                    $(".TransactionModal").modal('hide');
                }).fail(
                    function (jqXHR, textStatus, errorThrown) {
                        alert("create", jqXHR.responseText, 'error');
                    });
    
            });
    

    3- Для возврата данных вы можете легко вернуть сообщение JSON, например:

            [HttpPost]
            public IActionResult AddTransactionItem(SampleViewModel model)
            {
                model.CustomerTransactions = new List<SampleTransactionItemViewModel> {model.CustomerTransaction};
               // model.CustomerTransaction = null;
                return Json("any message here");
                //return PartialView("Modal/TransactionModal", output);
               // return View("FraudCheckBankAccountForm", model);
            }
    

    Вы имеете в виду использование $ .post Абдул Хади person nless; 13.06.2020

    Также как мне получить данные от контроллера обратно в представление, например. дата и сумма транзакции? person nless; 13.06.2020

Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: