【问题标题】:How to display the values from ajax success data to the html table?如何将 ajax 成功数据中的值显示到 html 表中?
【发布时间】:2020-06-09 02:06:57
【问题描述】:

我需要在我的 html 表中查看 ajax 成功消息 我的cshtml代码是:

@*@{Customer.Models.Customers cust = ViewBag.Customers;
}*@
@{ 
            }

    <center><h1 style="color:red">User details</h1></center>

<div>
    <table class="table">

        <tr>
            <td>ID</td>
            <td>res.Id</td>
        </tr>
        <tr>
            <td>FIRST NAME</td>
            <td>res.Fname</td>
        </tr>
        <tr>
            <td>LAST NAME</td>
            <td>res.Lname</td>
        </tr>
        <tr>
            <td>LOCATION</td>
            <td>res.Location</td>
        </tr>
        <tr>
            <td>Contact</td>
            <td>res.Contact</td>
        </tr>
        <tr>
            <td>Email</td>
            <td>res.Email</td>
        </tr>
        <tr>
            <td>Password</td>
            <td>res.Password</td>
        </tr>
        <tr>
            <td>Role</td>
            <td>res.Category</td>
        </tr>
        <tr>

    </table>
</div>
@section Scripts{
    <script>
            $.ajax({
                contentType: "application/json",
                type: "GET",
                url: "https://localhost:44397/api/Values/Details/" + id,
                success: function (data) {
                    alert('Welcome!');
                    res = data;


                   // window.location.href = "/Home/Details/" + data.id;
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $("#postResult").val(jqXHR.statusText);
                }
            });
    </script>
}

有没有办法使用成功数据传入每个表行? 也就是说,我希望 res 存储成功数据,然后将其传递给 res.Fname 等表字段(例如),它应该相应地显示数据。

【问题讨论】:

  • 你需要单独在一列或多列中显示值
  • 我需要在对应的列中显示每个值
  • 如果您使用剃须刀页面,repodemo 可以为您提供帮助。基本上有一个局部视图呈现主剃须刀页面内的 ajax 部分。该项目依赖于具有 ajax 支持的自定义 PagingTagHelper
  • 你有两个项目,一个 web 项目和一个 web api 吗?是不是想在web项目中使用ajax调用web api项目中的方法,然后在web项目中显示返回值?
  • @XueliChen 我有一个解决方案,其中包含 2 个控制器 api 和 home。我想要的只是将我的家庭控制器动作控件转换为我的 ajax 视图。但我无法在我的 html 表中获得该值。

标签: javascript html ajax asp.net-core asp.net-ajax


【解决方案1】:

您可以通过多种方式通过Ajax 回复来填充您的表格。这是您可以尝试的最易读和最流行的方式。见下面代码sn-p。

<table id="YourTableId" class="table table-bordered table-striped table-responsive table-hover">  
    <thead>  
        <tr>  
            <th align="left" class="yourTableTh">YourProperty</th>  
            <th align="left" class="yourTableTh">YourProperty2</th>  
            <th align="left" class="yourTableTh">YourProperty3</th>  
        </tr>  
    </thead>  
    <tbody></tbody>  
</table>                

<script>
        $.ajax({
            contentType: "application/json",
            type: "GET",
            url: "https://localhost:44397/api/Values/Details/" + id,
            success: function (data) {
                alert('Welcome!');
               // res = data;
                        var items = '';  
                        $.each(data, function (i, item) {  
                            var rows = "<tr>"  
                            + "<td class='yourTableTh'>" + item.YourProperty + "</td>"  
                            + "<td class='yourTableTh'>" + item.YourProperty2 + "</td>"  
                            + "<td class='yourTableTh'>" + item.YourProperty3 + "</td>"  
                            + "</tr>";  
                            $('#YourTableId tbody').append(rows);  
                        });  

               // window.location.href = "/Home/Details/" + data.id;
            },
            error: function (jqXHR, textStatus, errorThrown) {
                $("#postResult").val(jqXHR.statusText);
            }
        });
</script>

使用 C# Viewbag 的另一种方式:

 <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>Property Header</th>
                        <th>Property Header</th>
                        <th>Property Header</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var item in ViewBag.ViewBagName)
                    {
                        <tr>
                            <td>@item.PropertyName</td>
                            <td>@item.PropertyName</td>
                            <td>@item.PropertyName</td>
                        </tr>
                    }
                </tbody>
   </table>

如果您有任何其他问题,请告诉我。 希望这会有所帮助。

【讨论】:

  • 如果没有您提供的这种方法,有没有办法将成功数据调用到该表?
  • 有很多方法,但循环很常见,因为您必须填充一个表。但在某些JavaScript 框架中支持不循环响应数据。
  • 你期待哪种方式能给我提示?
  • @MdFarid我需要使用像我们在 C# 中使用 viewbag 一样的对象来获取我的表购买数据。在这里,我希望成功数据包含在变量中,并且我需要它来传递该表中的每个数据。有可能这样做吗?
  • 我强烈建议您尝试我的答案。它会起作用的。不建议这样做var yourVarable = '@ViewBag.ViewBagName';
【解决方案2】:

如果您需要单独在一列中显示值,请使用此类型

@*@{Customer.Models.Customers cust = ViewBag.Customers;
}*@
@{ 
            }

    <center><h1 style="color:red">User details</h1></center>

<div>
    <table class="table">

        <tr>
            <td>ID</td>
            <td id="Id"></td>
        </tr>
        <tr>
            <td>FIRST NAME</td>
            <td id="Fname"></td>
        </tr>
        <tr>
            <td>LAST NAME</td>
            <td id="Lname"></td>
        </tr>
        <tr>
            <td>LOCATION</td>
            <td id="Location"></td>
        </tr>
        <tr>
            <td>Contact</td>
            <td id="Contact"></td>
        </tr>
        <tr>
            <td>Email</td>
            <td id="Email"></td>
        </tr>
        <tr>
            <td>Password</td>
            <td id="Password"></td>
        </tr>
        <tr>
            <td>Role</td>
            <td id="Category"></td>
        </tr>
        <tr>

    </table>
</div>
@section Scripts{
    <script>
            $.ajax({
                contentType: "application/json",
                type: "GET",
                url: "https://localhost:44397/api/Values/Details/" + id,
                success: function (data) {
                    alert('Welcome!');
                    res = data;
                    document.getElementById("Id").innerHTML = res.Id;
                    document.getElementById("Fname").innerHTML= res.Fname;
                    document.getElementById("Lname").innerHTML= res.Lname;
                    document.getElementById("Location").innerHTML= res.Location;
                    document.getElementById("Contact").innerHTML= res.Contact;
                    document.getElementById("Email").innerHTML= res.Email;
                    document.getElementById("Password").innerHTML= res.Password;
                    document.getElementById("Category").innerHTML= res.Category;
                   // window.location.href = "/Home/Details/" + data.id;
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $("#postResult").val(jqXHR.statusText);
                }
            });
    </script>
}

我想它会帮助你:)

【讨论】:

  • 按 id 获取元素适用于表字段。我错误地使用了 value 它应该是 innerHTML
  • 好的,效果很好。您是否还可以建议使用循环为列表中的所有元素设置表格。怎么保存?
  • 分享一下表格设计你需要哪种方式显示列表
【解决方案3】:

您可以使用部分视图来包含表格数据并从 api 控制器返回PartialViewResult,然后从 ajax 的成功函数中显示部分视图。步骤如下:

_DetailsPartial

@model DemoTest.Models.User

<center><h1 style="color:red">User details</h1></center>

<div>
  <table class="table">
    <tr>
        <td>ID</td>
        <td>@Model.Id</td>
    </tr>
    <tr>
        <td>FIRST NAME</td>
        <td>@Model.Fname</td>
    </tr>
    <tr>
        <td>LAST NAME</td>
        <td>@Model.Lname</td>
    </tr>
    <tr>
        <td>LOCATION</td>
        <td>@Model.Location</td>
    </tr>
    <tr>
        <td>Contact</td>
        <td>@Model.Contact</td>
    </tr>
    <tr>
        <td>Email</td>
        <td>@Model.Email</td>
    </tr>
    <tr>
        <td>Password</td>
        <td>@Model.Password</td>
    </tr>
    <tr>
        <td>Role</td>
        <td>@Model.Category</td>
    </tr>
    <tr>
  </table>
</div>

Api 控制器,返回 PartialViewResult

[Route("api/[controller]/[action]")]
[ApiController]
public class ValuesController : ControllerBase
{
    private readonly DemoDbContext _context;
    public ValuesController(DemoDbContext context)
    {
        _context = context;
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> Details(int id)
    {
        var user = await _context.User.FindAsync(id);

        var myViewData = new ViewDataDictionary(new Microsoft.AspNetCore.Mvc.ModelBinding.EmptyModelMetadataProvider(), new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary()) 
        { { "User", user } };
        myViewData.Model = user;
        return new PartialViewResult()
        {
            ViewName= "_DetailsPartial",
            ViewData= myViewData
        };
    }
}

包含部分视图的主视图,使用ajax在&lt;div id="userdetail"&gt;&lt;/div&gt;中显示成功函数的结果

<div id="userdetail"></div>

@section Scripts{
 <script>
    var id = 1;
        $.ajax({
            //contentType: "application/json",
            type: "GET",
            url: "https://localhost:44343/api/Values/Details/" + id,
            success: function (data) {
                alert('Welcome!');
                $("#userdetail").html(data);


               // window.location.href = "/Home/Details/" + data.id;
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert('Failed!');
            }
        });
 </script>
}

结果:

关于局部视图的更多详细信息,您可以参考the official doc

【讨论】:

    最近更新 更多