简体   繁体   English

在按钮上渲染部分视图在div C#MVC 5中单击

[英]Rendering a Partial View on button click in a div C# MVC 5

I have been following the answers on here but can't seem to get it to work. 我一直在关注这里的答案,但似乎无法让它发挥作用。 I think it's firing my function and calling my controller but it isn't rendering my partial view. 我认为它正在触发我的函数并调用我的控制器,但它不会渲染我的局部视图。 Any help would be awesome. 任何帮助都是极好的。

Controller 调节器

public ActionResult Detail(int? id)
{
    if (id == null)
    {
       return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    User_Accounts user_accounts = db.User_Accounts.Find(id);
    if (user_accounts == null)
    {
        return HttpNotFound();
    }
    return PartialView("_Detail", user_accounts);
}

HTML HTML

<h2>Index</h2>
<div class="container left">

    <div class="panel-default panelbox" style="position:static">
        @*<p>
            @Html.ActionLink("Create New", "Create")*@

        @using (Html.BeginForm("Index", "Users", FormMethod.Get))
        {
            <p>
                Type: @Html.DropDownList("userType", "All")
            </p>
            <p>
                Last Name: @Html.TextBox("SearchString")
            </p>
        }
    </div>
    <div class="panel panel-default left">
        <div class="panel-heading">
            <label style="text-align:center">
                User
            </label>
        </div>
        <div class="table-responsive">
            <table id="UserTable" class="table-bordered table leftPanel table-condensed">
                @foreach (var item in Model)
                {
                    <tr>
                        <td>
                            <button data-url='@Html.Action("Detail", "Users", new { id = item.user_id_IN })' id="js-reload-details">@Html.DisplayFor(modelItem => item.DisplayName)</button>
                            @*@Html.ActionLink(item.DisplayName, "Detail", new { id = item.user_id_IN }, new { onclick = "renderPartial();" })*@
                        </td>
                    </tr>
                }
            </table>
        </div>
    </div>
</div>

<div>
    <label>Details</label>
    <div id="detailsDiv"></div>
</div>

Script 脚本

<script>
    $('.js-reload-details').click(function (evt) {

        var $detailDiv = $('#detailsDiv'),
            url = $(this).data('url');

        $.get(url, function (data) {
            $detailsDiv.replaceWith(data);
        });
        });
</script>

Let me know if you need anything else. 需要帮助请叫我。

You cant use data-url='@Html.Action("Detail", "Users", new { id = item.user_id_IN })' in your button to generate a url. 您无法在按钮中使用data-url='@Html.Action("Detail", "Users", new { id = item.user_id_IN })'来生成网址。 @Html.Action() is a method which calls you controller. @Html.Action()是一个调用控制器的方法。 What would be happening is that for each item in your model you would be hitting the Detail method of UsersController (performance must of been awful if you had a lot of items :) ). 将要发生的是,对于模型中的每个项目,您将访问UsersControllerDetail方法(如果您有很多项目,性能必须UsersController :))。

Since you appear to need only the one url ( /Users/Detail ) I suggest you just store the ID in data to minimize the html generated. 由于您似乎只需要一个URL( /Users/Detail ),我建议您只将ID存储在数据中以最小化生成的html。 As noted in the other answers you also need to use a class name for the button to prevent invalid html, and I also suggest using type="button" because the default (depending on the browser) may be "submit" (you don't have a form so does not matter in this case, but its good practice to get into). 如其他答案中所述,您还需要使用按钮的类名来防止无效的html,我还建议使用type="button"因为默认(取决于浏览器)可能是“提交”(你不喜欢)有一个表格所以在这种情况下并不重要,但它的良好做法进入)。 There is also no real need to use @Html.DisplayFor() unless your using a custom DisplayTemplate or have a [DisplayFormat] attribute on the property. 除非您使用自定义DisplayTemplate或在属性上具有[DisplayFormat]属性,否则也不需要使用@Html.DisplayFor()

Change the html to 将html更改为

<button type="button" data-id="@item.user_id_IN" class="js-reload-details">@item.DisplayName</button>

and the script to 和脚本

var url = '@Url.Action("Detail", "Users");
$('.js-reload-details').click(function() {
  $.get(url, { id: $(this).data('id') }, function (data) {
    $('#detailsDiv').html(data);
  });
});

Note you do not want to use replaceWith() in your case. 请注意,您不希望在您的情况下使用replaceWith() .replaceWith() would replace the actual div <div id="detailsDiv"></div> with the html your method returned, so the next time a user clicked on this or any other button, the method would be called, but <div id="detailsDiv"></div> no longer exists and nothing would happen. .replaceWith()将使用您的方法返回的html替换实际的div <div id="detailsDiv"></div> ,因此下次用户单击此按钮或任何其他按钮时,将调用该方法,但<div id="detailsDiv"></div>不再存在,什么都不会发生。

$('#detailsDiv').html('Hello world');

renders 呈现

<div id="detailsDiv">Hello world</div>

but

$('#detailsDiv').replaceWith('Hello world');

renders 呈现

Hello world

The id of your button id="js-reload-details" 你的按钮的id="js-reload-details"

  1. Mistake this code is repeated in a foreach loop. 错误此代码在foreach循环中重复。 which will cause multiple id's of the same name on your HTML page. 这会在HTML页面上导致多个同名的id。

  2. Your click event is on : '.js-reload-details'. 您的点击事件已开启:'。js-reload-details'。 which is a class: 这是一个类:

so make your code like this: 所以让你的代码像这样:

@foreach (var item in Model)
{
    <tr>
        <td>
            <button data-url='@Html.Action("Detail", "Users", new { id = item.user_id_IN })' class="js-reload-details">
                @Html.DisplayFor(modelItem => item.DisplayName)
            </button>
        </td>
    </tr>
}

One error I noticed in your jQuery is that you have $detailsDiv.replaceWith(data); 我在你的jQuery中注意到的一个错误是你有$detailsDiv.replaceWith(data); It should be $detailDiv according to your code: var detailDiv = $('#detailsDiv'); 它应该是$detailDiv根据你的代码: var detailDiv = $('#detailsDiv'); instead of $detailsDiv 而不是$detailsDiv

<script>
    $(document).ready(function(){
        $('.js-reload-details').click(function (evt) {

            evt.stopPropagation();
            var detailDiv = $('#detailsDiv');

            // TRY using the attr function: 
            var url = $(this).attr("data-url");

            $.get(url, function (data) {
                detailDiv.html(data);
            });
        });   
    });      
</script>

UPDATE: 更新:

<script>
    $(document).ready(function(){
        $('.js-reload-details').click(function (evt) {              
            evt.stopPropagation();
            var detailDiv = $('#detailsDiv');

            // TRY using the attr function: 
            var url = $(this).attr("data-url");

            $.get(url).success(function(result) {
                    detailDiv.html(result);
            });
    });
</script>

It's a good practice we use unique id's for our HTML elements. 我们的HTML元素使用唯一的id是一种很好的做法。 Since the following statement is going to be executed mulitple times 由于以下语句将被执行多次

  <button data-url='@Html.Action("Detail", "Users", new { id = item.user_id_IN })' id="js-reload-details">@Html.DisplayFor(modelItem => item.DisplayName)</button>

You will have multiple buttons with the same id. 您将拥有多个具有相同ID的按钮。 Instead of doing so, you could use a class. 你可以使用一个类,而不是这样做。

 <button data-url='@Html.Action("Detail", "Users", new { id = item.user_id_IN })' @class="js-reload-details">@Html.DisplayFor(modelItem => item.DisplayName)</button>

Then you have to correct your script: 然后你必须纠正你的脚本:

// Now we bound the click event in all the elements that contain
// the .js-reload-details class
$('.js-reload-details').click(function (evt) {  

    var $detailDiv = $('#detailsDiv');

    // Here was your the error
    var url = $(this).attr("data-url");

    $.get(url, function (data) {
        $detailsDiv.replaceWith(data);
    });
});

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

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