【问题标题】:MVC5 Partial View ExampleMVC5 局部视图示例
【发布时间】:2016-06-15 16:21:41
【问题描述】:

我正在寻求创建一个可重复使用的“员工查找”控件。

注意:我假设局部视图是最好的方法。

  1. 我想要页面上有多个按钮
  2. 每个按钮都会调用一个PartialView,每个按钮都有一个特定的文本框
  3. 每个部分将包含多个结果(项目)
  4. 单击其中一个结果时,我想填充按钮的文本框,该文本框进行调用,结果显示

我怎么能做到这一点,因为页面会有多个按钮和文本框?

【问题讨论】:

  • 反对者...关于如何让这个问题变得更好的任何建议?
  • 不是一个反对者,但格式更好一点,并添加一些你所拥有的和你尝试过的例子是在这种情况下给出的一般建议

标签: asp.net-mvc asp.net-mvc-partialview


【解决方案1】:

这个控件需要能够被多个按钮调用

那么,这些按钮会调用一个动作来呈现具有这些结果的部分吗?

我看到了多种方法来做到这一点。最简单的方法是:

<button id="btn1" class="btns" data-target="txt1" type="button">A</button>
<button id="btn2" class="btns" data-target="txt2" type="button">B</button>

<input type="text" id="txt1" />
<input type="text" id="txt2" />

<div id="render">

</div>

<script>
    var ajaxActive = false;

    $(function() {
        $(".btns").on('click', function () { // Bind the onclick of the button, so any button with this class may call the following function
            var _button = $(this);
            getItems(_button);
        });
    });

    function getItems(_button) {
        var bind = function (_button, results) {
            $("#render").empty();
            $("#render").append(results); // Append the partialview to the current view's div

            $("#render .itemResult").on('click', function () { // Bind the onclick of the result
                var resultValue = $(this).text(); // Or any other value that come from the result
                var targetId = "#" + _button.data('target'); // Id of the input (Target) which comes from the clicked button

                $(targetId).val(resultValue); // Change the input target value with the result one
            });
        };

        if (ajaxActive) {
            $.get('/Controller/Action') // Get the partialview 
           .done(function (results) {
               bind(_button, results);
           });
        }
        else {
            var results = simulateCall(); // Get the results
            bind(_button, results);
        }
    }

    function simulateCall() { // Simulate a call to the server
        return "<div class='items'> <div class='itemResult'>ABC</div> <div class='itemResult'>DEF</div> </div>";
    }
</script>

PS:这是一个有效的demo

请记住,我放置了某种“调用”来模拟它进入数据库

【讨论】:

  • 莱安德罗,感谢您抽出宝贵时间。这接近我正在寻找的东西。我相信我可以使用并调整它以满足我的需求。我假设您在上面分享的内容将在部分视图中,而按钮 A 和 B 将在我的视图中?我在现实世界中对此的用法是,可能会选择不止一名员工(例如:员工,然后是主管)。
  • 我建议您创建一个脚本,在其中放置您将用于此控件的所有 JS。然后其余的将在您的部分视图中。主视图只会调用(JS)initEmployeeControl();
  • 如果按钮从一个视图更改为另一个视图,这些按钮将保留在主视图上。或者,如果所有视图上的按钮都相同,则将其设置在局部视图上。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-11
  • 2017-10-02
  • 1970-01-01
  • 1970-01-01
  • 2016-08-19
  • 2015-02-03
  • 1970-01-01
相关资源
最近更新 更多