【问题标题】:Update a Multiple divs via ajax通过 ajax 更新多个 div
【发布时间】:2019-11-26 11:28:56
【问题描述】:

我有一个在数据库中添加书籍的表单, 我的表单中有一个模态窗口来创建发布者,如果发布者下拉列表中不存在指定的格式,我在部分视图中创建我的模态以添加发布者,

这是我的看法:

@model WebApplication3.Models.BookModel

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div id="CustomerList"></div>
<h2>Create New Book</h2>

<label class="text-@ViewBag.ClassName">
    @ViewBag.Message
</label>

@using (Html.BeginForm("CreateBook", "Book", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.TitleID, "TitleID", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("TitleID", null, "Select a Title", htmlAttributes: new { @class = "form-control" })
                @Html.ActionLink("Add New", "Create", "Title")
                @Html.ValidationMessageFor(model => model.TitleID, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.FormatID, "FormatID", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("FormatID", null, "Select a Format", htmlAttributes: new { @class = "form-control" })
                <a href="" class="" data-toggle="modal" data-target="#FormatModal">
                    Add New
                </a>
                @Html.ValidationMessageFor(model => model.FormatID, "", new { @class = "text-danger" })
            </div>
        </div>

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

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

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </div>
    </div>
}
<div class="modal fade" id="PublisherModal" tabindex="-1" role="dialog" aria-labelledby="publisherModalCenterTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            @Html.Partial("_Publisher")
        </div>
    </div>
</div>

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

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/jqueryajax")
}

这是我的 Publisher 部分视图:

@model WebApplication3.Models.PublisherModel

@using (Ajax.BeginForm("CreatePublisher", "Book", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "publisherForm", InsertionMode = InsertionMode.ReplaceWith }))
{
    <div id="publisherForm">
        <div class="modal-header">
            <h5 class="modal-title" id="publisherModalLongTitle">Create New Publisher</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>

        <div class="modal-body">

            @Html.AntiForgeryToken()

            <div class="form-horizontal">
                <div class="form-group">
                    <span class="text-@ViewBag.ClassName">
                        @ViewBag.Message
                    </span>
                </div>
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group">
                    @Html.LabelFor(model => model.Value, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Value, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Value, "", new { @class = "text-danger" })
                    </div>
                </div>

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

        </div>

        <div class="modal-footer">
            @Html.ActionLink("Manage", "Index", "Publisher", new { area = "" }, new { @class = "btn btn-link" })
            <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
            <input type="submit" value="Create" class="btn btn-primary" />
        </div>
    </div>
}

这是我的控制器

[HttpPost]
        [ValidateAntiForgeryToken]
        public PartialViewResult CreatePublisher([Bind(Include = "ID,Value,Description")] PublisherModel publisherModel)
        {
            ViewBag.TitleID = new SelectList(repoTitle.GetModels(), "ID", "Title");
            ViewBag.FormatID = new SelectList(repoFormat.GetModels(), "ID", "Value");

            PublisherModel publisher = repoPublisher.GetModels().FirstOrDefault(x => x.Value == publisherModel.Value);

            if (publisher == null)
            {
                if (ModelState.IsValid)
                {
                    repoPublisher.Insert(publisherModel);
                    ViewBag.PublisherID = new SelectList(repoPublisher.GetModels(), "ID", "Value", publisherModel.ID);
                    ViewBag.Message = $"Publisher \"{publisherModel.Value}\" Added Successfully";
                    ViewBag.ClassName = "success";
                    return PartialView("_Publisher");
                }
            }
            else
            {
                ViewBag.Message = $"Publisher \"{publisherModel.Value}\" Already Exsisted";
                ViewBag.ClassName = "danger";
            }

            ViewBag.PublisherID = new SelectList(repoPublisher.GetModels(), "ID", "Value");
            return PartialView("_Publisher",publisherModel);
        }

如何更改我的代码,如果新发布者插入数据库,发布者下拉菜单刷新并选择新插入的数据作为选定项?

【问题讨论】:

  • 您可以发布 ViewModel,我们无法在本地运行您的代码,因为您缺少 model.cs。

标签: c# asp.net model-view-controller


【解决方案1】:

关于问题

  • 我无法在本地运行您的代码。
  • 这些操作都可以通过JS来实现。
  • 我可以展示我的工具。 这是函数 gif:

    解决办法:

    1. 整体选择和添加选项。
// index.cshtml
<div>
    @await Component.InvokeAsync("AutoAddListValue")
</div>
//Component
@model List<string>

<h3>Default page</h3>

<div>
    <div>
        <p>Lists</p>
        <select name="select" class="" id="ComponentSelectId" onclick="ComponentSelectClick()">
            <option id="ComponentOptionId" style="width:auto">ComponentTest</option>
            @if (Model.Count != 0)
            {
                int count = Model.Count();
                for (int item = 0; item < count; item++)
                {
                    <option id="option">@Model[item].ToString()</option>
                }
            }
        </select>
    </div>

    <div>
        <input id="ComponentTestJsInput" class="d-none" value="132323" type="text" />
        <input id="ComponentBtnDisplay" value="Add" type="button" class="btn btn-primary" onclick="ComponentBtnDisplayClick()">
        <input id="ComponentBtnAdd" value="Add" type="button" class="btn btn-primary d-none" onclick="ComponentBtnAddClick()">
    </div>
</div>

  1. 为组件绑定数据。
    public class AutoAddListValueViewComponent : ViewComponent
    {
        private readonly SchoolContext _context;

        public AutoAddListValueViewComponent(SchoolContext context)
        {
            _context = context;
        }

        public async Task<IViewComponentResult> InvokeAsync(
            int maxPriority, bool isDone)
        {
            string MyView = "Default";

            var items = await GetListAsync();
            return View(MyView, items);
        }

        public async Task<List<string>> GetListAsync()
        {
            return await _context.Test.Select(o => o.Name).ToListAsync();
        }
    }
  1. 使用JS代码实现页面交互。
        var ComponentBtnDisplayClick = function () {

            $('#ComponentBtnAdd').removeClass("d-none");
            $('#ComponentTestJsInput').removeClass("d-none");
            $('#ComponentBtnDisplay').addClass("d-none");
        }

        var ComponentBtnAddClick = function () {
            //alert("666666");

            $('#ComponentBtnAdd').addClass("d-none");
            $('#ComponentTestJsInput').addClass("d-none");
            $('#ComponentBtnDisplay').removeClass("d-none");

            inputVal = $('#ComponentTestJsInput').val();
            //alert(inputVal);

            $.ajax({
                url: '/Test/SaveInputValue',
                data: {
                    name: inputVal
                },
                type: 'post',
                async: true,
                cache: false,
                success: function (data) {
                    //alert(data.code);
                    var option = "<option id='ComponentOptionId'>";
                    option += inputVal;
                    option += "</option>";
                    $("#ComponentSelectId").append(option);

                    var obj = document.getElementById("ComponentSelectId");                    
                    obj[obj.length - 1].selected = true;
                },
                error: function () {
                    alert('fail');
                }
            });
        }

其他代码

Source Code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多