Как отобразить значения из ajax данных успеха в таблицу html? - PullRequest
2 голосов
/ 25 февраля 2020

Мне нужно просмотреть сообщение об успехе ajax в моей таблице html, мой код cs html:

@*@{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 (например), и они должны отображать данные соответствующим образом.

Ответы [ 3 ]

2 голосов
/ 25 февраля 2020

Существует множество способов заполнить таблицу с помощью ответа Ajax. Здесь самый читаемый и популярный способ, которым вы можете попробовать. См. Фрагмент кода ниже.

<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>

Дайте мне знать, если у вас есть любой дополнительный вопрос. Надеюсь, это поможет.

1 голос
/ 26 февраля 2020

Вы можете использовать частичное представление для хранения данных таблицы и возврата PartialViewResult из контроллера API, а затем показать частичное представление из функции успеха 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, чтобы отобразить результат функции успеха в <div id="userdetail"></div>

<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>
}

Результат: enter image description here

Для получения дополнительной информации о частичном просмотре, Вы можете сослаться на официальное сделать c.

1 голос
/ 25 февраля 2020

Если вам нужно показать значение только в одном столбце, используйте этот тип

@*@{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>
}

Я думаю, это поможет вам:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...