如何使用ajax保存列表

本文关键字:列表 保存 ajax 何使用 | 更新日期: 2023-09-27 18:28:34

我在一个页面上显示了两个列表,Added和Available。如果您在"可用"列表中有一条记录,它将从该列表中删除并添加到"已添加"。Ajax用于刷新以显示新结果。但是,下面的代码可以实现这一点。我困惑于如何跟上每一份清单并使其持续下去。现在它只根据初始模型数据进行记忆。任何建议都很好我在这方面很努力(我还是新手)。

jquery ajax:

<script>
    function AddProperty(propertyid) {
        var currentProperties = @Html.Raw(Json.Encode(Model.Added));
        var availableProperties = @Html.Raw(Json.Encode(Model.Avail));
        if (currentProperties.Id == null) {
            var x = {
                "Id": 0,
                "Name": "na",
                "Value": "na"
            };
            currentProperties.push(x);
        }
        $.ajax({
            url: "/Home/AddProperty",
            type: "POST",
            data: JSON.stringify({ PropertyId: propertyid, editList: currentProperties, availList: availableProperties }),
            dataType: "json",
            contentType: "application/json",
            success: function (result) {
                $("#edittable tr").remove();
                $("#availtable tr").remove();
                for (var i = 0; i < result.FirstList.length; i++) {
                    if (result.FirstList[i].Id > 0) {
                        $('#edittable').append(
                            '<tr><td>'+result.FirstList[i].Name+':</td>' +
                           '<td><input type="text" id=editval"' + i+ '" value="'+result.FirstList[i].Value+'"></td>' +
                           '<td>' +
                               '<a class="btn-primary" style="cursor:pointer" onclick="DeleteProperty('+result.FirstList[i].Id+')" ><span class="glyphicon glyphicon-remove" /></a>' +
                        '</td></tr>'
                        );
                    } else {
                        $('#edittable').append('<tr><td>No configuration values added.</td></tr>');
                    }
                }                    
                for (i = 0; i < result.SecondList.length; i++) {
                    if (result.SecondList[i].Id > 0) {
                        $('#availtable').append(
                            '<tr><td><a class="btn-primary" style="cursor:pointer" onclick="AddProperty('+result.SecondList[i].Id+')" ><span class="glyphicon glyphicon glyphicon-plus-sign" /></a></td>' +
                            '<td>'+result.SecondList[i].Name+':</td>' +
                            '</td></tr>'
                        );
                    } else {
                        $('#availtable').append('<tr><td>No configuration values available.</td></tr>');
                    }
                }  
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert('error: ' + thrownError);
            }
        });
    }
</script>

视图模型:

public class ViewModel
{
    public int Id { get; set; }
    public string Desc { get; set; }
    public List<Children> Added { get; set; }
    public List<Children> Avail { get; set; }
}
public class Children
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }
}

控制器:

[HttpPost]
public ActionResult AddProperty(int propertyId, List<Children> editList, List<Children> availList)
{
    var newEditList = new List<Children>();
    //add object to added list
    var newEditRow = availList.Where(edit => edit.Id == propertyId).ToList();
    newEditList.AddRange(newEditRow);
    //remove from available list
    var newAvailList = availList.Where(avail => avail.Id != propertyId).ToList();
    var result = new { FirstList = newEditList, SecondList = newAvailList };
    return Json(result, JsonRequestBehavior.AllowGet);
}

查看代码:

@model ViewModel
@using (Html.BeginForm())
{
   <div class="panel panel-primary" id="ConfigValueContainer">
    <div class="panel-heading">
        <h2>Our Values</h2>
        <hr />
    </div>
       <div class="panel-body">
           <div class="lineup-tables">
           <h3>Edit Values</h3>
           <table id="edittable">
               @*<tr>
                   <td colspan="2">Message Type: @Model.Desc</td>
               </tr>*@
               @if (@Model.Added.Any())
               {
                   foreach (var added in Model.Added)
                   {
                       <tr>
                           <td>@Html.DisplayFor(model => added.Name):</td>
                           <td>@Html.TextBoxFor(model => added.Value)</td>
                           <td>
                               <a class='btn-primary' style='cursor:pointer' onclick='DeleteProperty(@added.Id)' ><span class='glyphicon glyphicon-remove' /></a>
                           </td>                  
                       </tr>
                   }
               }
               else
               {
                   <tr>
                       <td>No configuration values added.</td>
                   </tr>
               }
           </table>
       </div>
           <div class="lineup-tables">
           <h3>Add New Values</h3>
               <table id="availtable">
                   @if (@Model.Avail.Any())
                   {
                       foreach (var avail in Model.Avail)
                       {
                           <tr>
                                <td>
                                    <a class='btn-primary' style='cursor:pointer' onclick='AddProperty(avail.Id)' ><span class='glyphicon glyphicon-plus-sign' /></a>
                                </td>  
                               <td>@Html.DisplayFor(model => avail.Name)</td>
                           </tr>
                       }
                   }
                   else
                   {
                       <tr>
                       <td>No configuration values available.</td>
                   </tr>
                   }
               </table>
               </div>
           <br/>
           <div class="panel-footer">
               <input type="submit" disabled class="btn btn-primary" value="Save" id="btnSave" />
               <span id="close" class="btn btn-primary cancelLink">Cancel</span>
               <div class="clearfix"></div>
           </div>
       </div>
       </div>
}

如何使用ajax保存列表

首先,向每个表行添加隐藏输入,以便轻松获取所需的一切。

#edittable 
<tr> 
  <input type="hidden" class="id" value="@added.Id" />
  <input type="hidden" class="name" value="@added.Name" />
  <input type="hidden" class="value" value="@added.Value" />
  <td>@Html.DisplayFor(model => added.Name):</td> 
  <td>@Html.TextBoxFor(model => added.Value)</td> 
  <td> 
    <a class='btn-primary' style='cursor:pointer' onclick='DeleteProperty(@added.Id)' ><span class='glyphicon glyphicon-remove' /></a> 
  </td>                   
</tr> 
#availtable 
<tr> 
   <input type="hidden" class="id" value="@avail.Id" />
   <input type="hidden" class="name" value="@avail.Name" />
   <input type="hidden" class="value" value="@avail.Value" />
   <td> 
     <a class='btn-primary' style='cursor:pointer' onclick='AddProperty(avail.Id)' ><span class='glyphicon glyphicon-plus-sign' /></a> 
   </td>   
   <td>@Html.DisplayFor(model => avail.Name)</td> 
</tr> 

现在,不要像您那样使用currentProperties和available Properties,而是尝试以下操作:

function AddProperty(propertyid) {
  var currentProperties = [];
  var availableProperties = [];
  $('#edittable tr').each(function() {
    var row = $(this);
    var child = {
      Id: row.find('.id').val(),
      Name: row.find('.name').val(),
      Value: row.find('.value').val()
    };
    currentProperties.push(child);
  });
  $('#availtable tr').each(function() {
    var row = $(this);
    var child = {
      Id: row.find('.id').val(),
      Name: row.find('.name').val(),
      Value: row.find('.value').val()
    };
    availableProperties.push(child);
  });
  // Use them in your ajax call

这可能需要一些调整,但应该会让你走上正确的道路。