具有动态部分视图创建的MVC Ajax

Int*_*eer 15 asp.net-mvc-4

如何创建将调用动态部分视图的动态ajax.actionlinks.

例如:

  • 我有一个页面,将生成x个评论
  • 每条评论都可以上下投票(单独)
  • 向上投票和向下投票的数量计入一个整数
  • 每个注释div都有自己的ajax.actionlink
  • 每个ajax.actionlink都会将注释的ID传递给控制器
  • 控制器将计算总票数并调用局部视图以使用正确的ID显示回div.

到目前为止我做了什么:

  • 我已经能够创建成功的ajax.actionlink

  • 这将召唤一个控制器并总结投票

  • 这将调用局部视图并显示投票

问题是什么

  • 我不想硬编码30-100个不同的ajax.actionlinks来调用30-100个硬编码的部分视图.

我该如何动态完成此操作?

现有守则:

我的剃刀视图里面的我的ajax.actionlink

 @Html.Raw(Ajax.ActionLink("[replacetext]", "VoteUp",
                new { UserPostID = @Model.Id },
                        new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "CountVote" }).ToHtmlString().Replace("[replacetext]",
                        "<img src=\"/Images/up_32x32.png\" />"))
Run Code Online (Sandbox Code Playgroud)

我的div在同一个剃刀视图中显示从局部视图返回的结果.

<div id="CountVote" class="postvotes"></div>
Run Code Online (Sandbox Code Playgroud)

我的控制器

    public PartialViewResult VoteUp(int UserPostID)
    {
        try
        {
            UserVotes vote = new UserVotes();
            vote.SubmitedVote = 1;
            vote.UserId = Convert.ToInt32(Session["id"]);
            vote.UserPostID = UserPostID;
            ViewBag.SumVotes = postRepository.InsertUserPostVote(vote);

        }
         catch (Exception e)
        {
            xxx.xxx.xxxx().Raise(e);
        }
        return PartialView("_TotalVotes");
    }
Run Code Online (Sandbox Code Playgroud)

最后我的部分视图(_TotalVotes.cshtml)

@ViewBag.SumVotes
Run Code Online (Sandbox Code Playgroud)

现在,我对Viewpost的主视图使用viewbag在循环中显示注释.

foreach (var item in (List<UserComment>)ViewData["Comments"])
            {
                CommentVote = "cv" + i.ToString();
    <div class="postlinewrapper">
        <div class="postvotesframe">
            <div class="postvotes">
                @Html.Raw(Ajax.ActionLink("[replacetext]", "VoteUp",
                        new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "CountVote" }).ToHtmlString().Replace("[replacetext]",
                        "<img src=\"/Images/up_32x32.png\" />"))
            </div>

            <div id="@CommentVote" class="@CommentVote">0</div>
            <div class="postvotes">
                @Html.Raw(Ajax.ActionLink("[replacetext]", "VoteDown",
                        new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "CountVote" }).ToHtmlString().Replace("[replacetext]",
                        "<img src=\"/Images/down_32x32.png\" />"))
            </div>
        </div>
        <div class="postleftbar">
            @Html.Raw(item.Comment)
        </div>
        <div class="postrightbar">
            <div>
                <div class="post_spec">
                    <div class="post_spec_title">Call Sign:  </div>
                    <div class="post_spec_detail">@item.CallSign</div>
                </div>
                <div class="post_spec">
                    <div class="post_spec_title">When:  </div>
                    <div class="post_spec_detail">@item.CommentDate.ToString("dd/MM/yyyy")</div>
                </div>
            </div>
            <br />
            <br />
        </div>
    </div>
                i += 1;
            }
Run Code Online (Sandbox Code Playgroud)

我已实施登录以上下增加或减少投票:

 public PartialViewResult VoteUp(int userPostId)
        {
            try
            {
                UserVotes vote = new UserVotes();
                vote.SubmitedVote = 1;
                vote.UserId = Convert.ToInt32(Session["id"]);
                vote.UserPostID = userPostId;
                ViewBag.SumVotes = postRepository.InsertUserPostVote(vote);

            }
             catch (Exception e)
            {
                xxxx.xxxx.xxxx().Raise(e);
            }
            return PartialView("_TotalVotes");
        }

        public PartialViewResult VoteDown(int userPostId)
        {
            try
            {
                UserVotes vote = new UserVotes();
                vote.SubmitedVote = -1;
                vote.UserId = Convert.ToInt32(Session["id"]);
                vote.UserPostID = userPostId;
                ViewBag.SumVotes = postRepository.InsertUserPostVote(vote);

            }
            catch (Exception e)
            {
                xxx.xxxx.xxxx().Raise(e);
            }
            return PartialView("_TotalVotes");
        }
Run Code Online (Sandbox Code Playgroud)

现在所有这些代码都适用于1 ajax调用,但我需要的是动态显示单独的ajax调用单独的div.

Jas*_*sen 5

试试这种方式.

主要观点

我假设您的模型具有CommentsComment项的集合属性

@model MyNamespace.CommentAndOtherStuff

<ul>
    @foreach(item in Model.Comments)
    {
      <li>
          <a href="@Url.Action("VoteUp", "VoteControllerName", new { UserPostId = item.Id })" 
             class="vote-link"
             data-id="@item.Id">@item.Votes</a><img src="vote.jpg" />
      </li>
    }
</ul>
Run Code Online (Sandbox Code Playgroud)

而你的控制器只返回一个名为VoteResultJSON 的类.

[HttpPost]
public ActionResult VoteUp(int UserPostID)
{
    ...
    var model = new VoteResult
    {
        UserPostID = UserPostID,
        Votes = service.tallyVote(UserPostID)
    };

    return Json(model);
}
Run Code Online (Sandbox Code Playgroud)

现在用jQuery事件处理程序挂起所有这些并设置一个AJAX调用

$(document).ready(function() {

    $("a.vote-link").on("click", function(event) {
        event.preventDefault();
        var link = $(this);  // the link instance that was clicked
        var id = link.attr("data-id");
        var url = link.attr("href");

        $.ajax({
            url: url,
            type: "post"
        })
        .done(function(result) {
            // JSON result: { UserPostID: 1, Votes: 5 }

            // replace link text
            link.html(result.Votes);
        });
    });

});
Run Code Online (Sandbox Code Playgroud)

但我想要部分视图html fagment.

[HttpPost]
public ActionResult VoteUp(int UserPostID)
{
    ...
    var model = new VoteResult
    {
        UserPostID = UserPostID,
        Votes = service.tallyVote(UserPostID)
    };

    return PartialView("_TotalVotes", model);
}
Run Code Online (Sandbox Code Playgroud)

_TotalVotes partial

@model MyNamespace.VoteResult

@if (Model.Votes < 0)
{
    <span class="unpopular">@Model.Votes</span>
}
else
{
    <span class="awesome">@Model.Votes</span>
}
Run Code Online (Sandbox Code Playgroud)

并调整AJAX回调

.done(function(result) {
    link.html(result);
});
Run Code Online (Sandbox Code Playgroud)

现在你可以为链接片段写一个帮助器,但是在我看来它会混淆(这是一个判断调用).这里你真正需要的是你的javascript将绑定的类名和data-id.