简体   繁体   English

由模式弹出窗口提交的父页面中的ASP.NET MVC更新下拉列表

[英]Asp.net mvc updating dropdownlist in parent's page submitted by a modal popup

I have a main page that loads a partial view which is using 我有一个主页加载正在使用的部分视图

Html.BeginCollectionItem("employees") Html.BeginCollectionItem(“ employees”)

because I am using a jQuery tab. 因为我使用的是jQuery标签。 (so the user can add more employee forms) (以便用户可以添加更多员工表格)

Inside of my Employee partial view has a dropdownlist for selecting country, and it also has a link that pops up a modal to add a new country. 在我的Employee局部视图中,有一个用于选择国家/地区的下拉列表,并且还具有一个链接,该链接会弹出一个添加新国家/地区的模式。 Here, what I want to do is, after submitting the modal and when it is closed, I would like the dropdownlist to be refreshed right away so that the user can see the new updated list. 在这里,我想做的是,在提交模式并关闭模式之后,我希望立即刷新下拉列表,以便用户可以看到新的更新列表。

How can this be done when the Id of dropdownlist is dynamically changed as the user adds more tab? 当用户添加更多标签时动态更改dropdownlist的ID时,该怎么办?

Company.cshtml: Company.cshtml:

@using (Html.BeginForm("Create", "CompanyForm", FormMethod.Post))
{
    <p>Company Info</p>
    @Html.EditorFor(m => m.companyName, new { htmlAttributes = new { @class = "form-control" } })  

    <div id="tabs">
        <ul>
            <li><a href="#tabs-employee">Employee 1</a> <span class="ui-icon ui-icon-close" role="presentation">Remove Tab</span></li>
        </ul>
        <div id="tabs-employee">              
            @Html.Action("Employee")
        </div>            
    </div>
    <button type="submit">Submit</button>
}    

<script>
//tab codes...
</script>

Employee.cshtml: Employee.cshtml:

<div class="editorRow">
    @using (Html.BeginCollectionItem("employees"))
{
    <!-- Dropdown-->
    @Html.DropDownListFor(m => m.CountryId, (SelectList)ViewBag.CountryList, "-- Select --", new { @class = "form-control" })
    <!-- Link-->
    <a href="#" class="btn btn-info btn-md" data-toggle="modal" data-target="#countryModal">Add Country</a>
}
</div>

<!-- Modal -->
<div class="modal fade" id="countryModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">Add Country</h4>
        </div>
        <div class="modal-body">
            <div class="ajax-dynamic-get-data-form" />
        </div>
    </div>
</div>
</div>

<script>
$('#countryModal').on('show.bs.modal', function (event) {
var url='@Url.Action("NewEmployee")';
$.ajax({
    type: "GET",
    url: url,
    data: JSON,
    cache: false,
    success: function (data) {          
        $('#countryModal').find('.ajax-dynamic-get-data-form').html(data);
    },
    error: function (err) {
        console.log(err);
    }
});
})
</script>

NewCountry.cshtml: NewCountry.cshtml:

@{
    Layout = null;
}

@using (Html.BeginForm("PostNewCountry", "CompanyForm", FormMethod.Post, new { id = "postOfferForm" }))
{

<label>Employee Name</label>
@Html.TextBoxFor(x => x.CountryName, new { @class = "form-control" })


<div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-default">Save</button>
</div>
}

<script>
$("#postOfferForm").submit(function () {
    $.ajax({
        url: "/CompanyForm/PostNewCountry",            
        type: "POST",
        data: $(this).serialize(),
        datatype: "json",
        success: function (response) {
            if (response.status === "success") {                   
                $('#countryModal').modal('hide');

            } else {
                alert(response.errorMessage);
                $('#countryModal').modal('hide');
            }
        }
    });
    return false;
});         
</script>

Edited 已编辑

Another problem after Stephen gave me a hint to solve the above issue, is that the modal is only popping up in tab1. 在斯蒂芬给我一个提示来解决上述问题之后的另一个问题是,该模式仅在tab1中弹出。 How can I also update the dropdownlist in all tabs? 如何在所有标签中更新下拉列表?

You have a number of problems with your implementation. 您的实现有很多问题。

First your generating duplicate scripts (in both your Employee.cshtml and NewCountry.cshtml partials), and these need to be moved to the main view so there is only one copy loaded. 首先,您生成的重复脚本(在Employee.cshtmlNewCountry.cshtml ),并且需要将这些脚本移至主视图,以便仅加载一个副本。

In addition, it is only necessary to have one modal form for creating a new Country in the main view, and include a button in each Employee partial to open the modal (currently you just repeating a whole lot of unnecessary html and making unnecessary ajax calls to populate the modal form repeatedly - you can just include the form initially, or if you want to populate it using ajax, include a 'flag' that indicates if its been loaded or not so only one ajax call is made) 此外,只需要在主视图中使用一个模式窗体来创建新的Country ,并在每个Employee部分中包含一个按钮即可打开模式(当前,您只需重复很多不必要的html并进行不必要的ajax调用)要重复填充模式表单-您可以只在最初包含该表单,或者如果您想使用ajax填充该表单,请添加一个“ flag”(表示是否已加载该表单),因此仅进行一次ajax调用)

To update the dropdownlists with an option for the new Country you have added, give then a class name 要使用添加的新Country的选项更新下拉列表,请提供一个类名

@Html.DropDownListFor(m => m.CountryId, ... new { @class = "form-control country" })

Then in your ajax success callback update each existing dropdown. 然后在ajax成功回调中更新每个现有下拉列表。 You have not indicated what your PostNewCountry() method returns, but assuming it returns just the ID of the new Country , then 您尚未说明PostNewCountry()方法返回什么,但是假设它仅返回新Country的ID,则

success: function (response) {
    var name = $('#CountryName').val(); // assumes you have only one modal form
    var countries = $('.country');
    $.each(countries, function(index, item) {
        var option = $('<option></option>').val(response).text(name);
        $(this).append(option);
    }
}

Your second issue ( the modal is only popping up in tab1 ) is as a result of all duplicate id attributes which is invalid html. 您的第二个问题( 模式仅在tab1中弹出 )是由于所有重复的id属性(无效的html)导致的。 This will be solved by having only one modal as noted above, but with your current implementation, you need to remove the id attributes and use class names instead. 这将通过仅使用如上所述的一个模式来解决,但是在当前的实现中,您需要删除id属性并改用类名。 When you use id selectors in jQuery, it will only select the first one with that id , so neither $('#countryModal').on(... , and $("#postOfferForm").submit(... will work correctly. 当您在jQuery中使用id选择器时,它只会选择具有该id的第一个选择器,因此$('#countryModal').on(...$("#postOfferForm").submit(...都不会正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM