更新ajax发布后的div列表

时间:2013-02-28 10:36:26

标签: javascript asp.net ajax asp.net-mvc

我有这段代码加载了一些div

<input class="input-large" placeholder="Notat" id="txtNewNote" type="text">
        <button class="btn" id="btnAddNote" type="button">Lagre</button>

@foreach (var item in Model.UserNotes)
    {
        <div class="alert" id="divNote-@item.UserNoteID">
        <button type="button" class="close" onclick="NoteDeleteClicked(@item.UserNoteID)" id="btnCloseNote">&times;</button>
        <strong>@item.User.Name - @item.Added</strong><br />
            @item.Text
        </div>
    }

然后当用户输入更多文本时运行此javascript:

  var Text = $("#txtNewNote").val();
  var Added = Date.now();
  vvar UserID = $("#hiddenUserID").text();
  $.post("/api/apiUserNotes",{ Text : Text, Added: Added, UserID: UserID }, function()        { //need functianality for updating the list of divs above });

任何人都可以在这里指出我正确的方向。我不能在帖子完成后创建div,因为我需要从数据库中获取数据,以便div中的信息正确。

2 个答案:

答案 0 :(得分:0)

您可以通过以下方式访问以上Div,并根据您的要求进行更新。

 $.post("/api/apiUserNotes",{ Text : Text, Added: Added, UserID: UserID },
 function()
  { 
   //need functianality for updating the list of divs above 
   $("div.alert").each(....)
});

答案 1 :(得分:0)

主要有两种方法:

  1. apiUserNotes返回HTML - 由于您只有一个模板,因此这种方法更容易维护。但是,从某种意义上来说,HTML也有更大的限制性,因为HTML很适合展示,但操控它并不是很重要。

  2. apiUserNotes返回JSON - 这更灵活,因为几乎任何东西都可以使用JSON API,从HTML到原生iOS或Android应用,因为它更容易操纵。这也是更多的工作,因为你在服务器端(你的Razor视图)以及客户端(你的HTML / JavaScript)都有模板。

  3. 这或多或少是#1的样子:

    首先制作部分视图以显示用户注释:

    _UserNotes.cshtml:

    <div id="user-notes">
        @foreach (var item in Model.UserNotes)
        {
            <div class="alert" id="divNote-@item.UserNoteID">
                <button type="button" class="close" onclick="NoteDeleteClicked(@item.UserNoteID)" id="btnCloseNote">&times;</button>
                <strong>@item.User.Name - @item.Added</strong><br />
                    @item.Text
            </div>
        }
    </div>
    

    获得此部分视图后,您可以从视图中使用它:

    <input class="input-large" placeholder="Notat" id="txtNewNote" type="text">
    <button class="btn" id="btnAddNote" type="button">Lagre</button>
    @Html.Partial("_UserNotes")
    

    来自apiUserNotes行动:

    public PartialViewResult apiUserNotes(string text, DateTime added, int userID)
    {
        // TODO: save new note
        var notes = yourRepo.GetUserNotes(userID);
        return PartialView("_UserNotes", notes);
    }
    

    最后,您的客户端脚本只会覆盖包含所有用户注释的div:

    var data = {
        text = $("#txtNewNote").val(),
        added = Date.now(),
        userID = $("#hiddenUserID").text()
    };
    
    $.post("/apiUserNotes", data, function (result) {
        $('#user-notes').html(result);
    });
    

    当然有更有效的方法。例如,您无需重新加载所有用户注释;只有你刚才添加的那个。但希望这能让你开始。

相关问题