【问题标题】:Return partialview tag with a model using ajax/json使用 ajax/json 返回带有模型的部分视图标记
【发布时间】:2020-06-30 15:58:12
【问题描述】:

我需要一些帮助来显示来自数据库的正确过滤数据。 如果用户按下按钮,则会显示一个带有部分视图的屏幕。每个局部视图都是一个模型,其中包含自己的数据。我使用 ajax 使其更具动态性。

控制器:

    [HttpPost]
    public JsonResult Test2(int id)
    {
        List<Location> p = _context.Locations.Where(x => x.CategoryId.Equals(id)).ToList();
        return Json(p);
    }

局部视图:

<div class="sidebar_container" id="style-3">
    <div class="sidebar_list" id="locatieLijstAfter">

    </div>
</div>

脚本:

function yoo(id) {
    $.ajax({
        type: 'POST',
        url: '/Home/Test2',
        data: { 'id': id },
        success: function(result){
            var p = "";
            for (var i = 0; i < result.length; i++) {
                $('#locatieLijstAfter').html('< partial name="../Shared/_LocationItemPartial.cshtml" ' + 'model = "' + result[i] + '" /> ');
            }

        }

这就是我现在拥有的,但是当我运行它时会发生这种情况。 enter image description here

【问题讨论】:

    标签: jquery html json ajax


    【解决方案1】:

    &lt;partial&gt; 标记是在服务器端处理的 Razor 构造。这不是 JS 或纯 HTML 能理解的。

    要使逻辑以您需要的方式工作,您需要更改您的操作,以便它从部分视图返回 HTML 而不是 JSON。

    该模式看起来像这样,但显然我正在简化,因为您的模型或预期的 HTML 输出缺乏具体细节。

    [HttpPost]
    public IActionResult Test2(int id)
    {
        List<Location> p = _context.Locations.Where(x => x.CategoryId.Equals(id)).ToList();
        return View("PartialViewName", p);
    }
    
    @model List<Location>
    
    @foreach(var item in Model) 
    {
      <div class="sidebar_container">
        <div class="sidebar_list">@item.Foobar</div>
      </div>
    }
    
    function yoo(id) {
      $.ajax({
        type: 'POST',
        url: '/Home/Test2',
        data: { 'id': id },
        success: function(result) {
          $('#container').html(result);
        }
      });
    }
    

    【讨论】:

    • 我有一些问题。 #container 是什么意思? @item.Foobar 是什么?感谢您回答顺便说一句
    • 它们只是示例值。 #container 表示要使用通过 AJAX 请求检索到的部分内容来更新 DOM 中的元素。 @item.Foobar 旨在成为要在部分中输出到 HTML 的模型中项目的属性
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多