Razor Core 2.2: установить элемент cshtml в качестве переменной - PullRequest
0 голосов
/ 07 октября 2019

На мой взгляд, я хочу назначить частичное представление переменной, которую затем можно использовать в функции javascript. Есть ли хороший способ сделать это?

Итак, я хочу сделать что-то вроде:

var foo = <partial name="_partial.cshtml"/>

тогда я мог бы использовать foo позже, например:

<script>
    $("#button").on("click", () => $("#table tbody").append(@foo));
</script>

Ответы [ 2 ]

2 голосов
/ 07 октября 2019

Вы можете сохранить частичную переменную в переменной ac # и получить ее при нажатии кнопки.

C #:

@{
  IHtmlString partialView = Html.Partial("yourview", yourmodel);
}

Javascript:

<script>
    var partialView = `@partialView`;
    $("#button").on("click", () => $("#table tbody").append(partialView));
</script>
1 голос
/ 07 октября 2019

Вы можете вернуть PartialView из контроллера и показать его в функции успеха ajax. Ниже приведена простая демонстрация, к которой можно обратиться:

Модель продукта:

 public class Product
{
    public int Id { get; set; }
    public string  Name { get; set; }
    public int Price { get; set; }
}

Основной вид:

@model IEnumerable<Product>

<table class="table">
<thead>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Price)
        </th>
        <th></th>
    </tr>
</thead>
<tbody>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Price)
            </td>
            <td>
                <button class="btnAdd" onclick="GetProduct(@item.Id)">Add To Cart</button>
            </td>
        </tr>
    }
</tbody>
</table>

<div>
  <label>ProductCart</label>
  <table id="table">
    <thead>
        <tr>
            <th>
                Name
            </th>
            <th>
                Price
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>


@section Scripts
{
<script type="text/javascript">
    function GetProduct(id) {
        $.ajax({
            type: "get",
            url: "/home/getpartial?id="+id,
            success: function (result) {
                console.log(result);
                $("#table tbody").append(result);
            }
        });
    }
</script>
}

PartialView:

@model Product
<tr>
  <td>
     @Html.DisplayFor(model => model.Name)
  </td>
  <td>
     @Html.DisplayFor(model => model.Price)
  </td>
</tr>

Контроллер:

public async Task<IActionResult> Products()
    {
        var products =await  _context.Products.ToListAsync();
        return View(products);
    }

    public IActionResult GetPartial(int id)
    {
        var model = _context.Products.Find(id);
        return PartialView("_ItemPartial", model);
    }

Результат:

enter image description here

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