MVC 4 Ajax.Action链接无法正常工作

Tom*_*Tom 5 c# asp.net-ajax html.actionlink razor asp.net-mvc-4

我正在尝试使用Ajax调用创建一个MVC网站.我没有直接使用jquery的问题,但是当我使用@ Ajax.ActionLink时,我没有得到我想要的结果.这是我的观点:

    <script type="text/javascript">
        function deleteComment(id) {
            $.post(
                "/Role/AjaxTest",
                //{ id: id }, 

                function (data) {
                    $("#testtarget").html(data);               
                });
         }
    </script>


    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
    <h2>TITLE</h2>
    <p>
 @Ajax.ActionLink("Ajax Test", "AjaxTest", "Role", new AjaxOptions{UpdateTargetId="testtarget",HttpMethod = "Get" , InsertionMode = InsertionMode.Replace }) 
    </p>
    <table>    
    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.RoleName)
            </td>
            <td>
              <a onclick="deleteComment('@item.RoleId'); return false;" href="#">Delete</a>
                @Html.ActionLink("Delete", "Delete", new { id=item.RoleId })

            </td>
        </tr>
    }
    </table>
    <div id="testtarget">Test Div</div>
Run Code Online (Sandbox Code Playgroud)

这是我的Controler数据:

public string AjaxTest()
{
    return "Some random text";
}
Run Code Online (Sandbox Code Playgroud)

我对Jquery的调用完美,文本出现在div中,但我的actionlink只是将我重定向到:localhost/Role/AjaxTest,所以我只是在银行浏览器中显示消息.

知道这里有什么问题吗?

非常感谢提前!

Dar*_*rov 9

确保已将jquery.unobtrusive-ajax.js脚本添加到页面中:

<script type="text/javascript" src="~/scripts/jquery.unobtrusive-ajax.js"></script>
Run Code Online (Sandbox Code Playgroud)

或者如果您正在使用捆绑包(这是推荐的方法),请确保您已包含包含此脚本的捆绑包.例如,当您使用将成为~/bundles/jqueryval捆绑包的Internet模板创建新的ASP.NET MVC 4项目时:

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
    "~/Scripts/jquery.unobtrusive*",
    "~/Scripts/jquery.validate*")
);
Run Code Online (Sandbox Code Playgroud)

因此,请确保它在jquery包之后包含在您的视图中:

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
Run Code Online (Sandbox Code Playgroud)

或者只是将它们组合成一个捆绑包.这完全取决于您的要求以及是否需要不显眼的jquery验证支持.

我还建议你让你的控制器动作返回ActionResult而不是字符串:

public ActionResult AjaxTest()
{
    return Content("Some random text");
}
Run Code Online (Sandbox Code Playgroud)