如何在通过Ajax生成的锚标记内加载局部视图

时间:2016-06-28 23:51:14

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

我有一个带有下拉列表的表单。选择选项时,我进行ajax调用以在视图中动态添加链接列表。当我点击其中一个链接时,我想用PostListSubCategory()方法返回的部分视图更新现有页面。

目前,点击其中一个链接会进行重定向,并在新页面中显示部分视图。如何更新现有页面?

<script language="javascript" type="text/javascript">
function GetSubCategory(_categoryId) {
    var procemessage = "<a='0'> Please wait...</a>";
    $("#SubCategoryID").html(procemessage).show();
    var url = "/Posts/GetSubCategoryById/";

    $.ajax({
        url: url,
        data: { categoryid: _categoryId },
        cache: false,
        type: "POST",
        success: function (data) {
            var markup = "";
            for (var x = 0; x < data.length; x++) {
                var num = data[x].Text;
                markup += "<a href='/posts/postlistsubcategory?subcategoryid=" + data[x].Text + "'>" + data[x].Text + "</a><br />";
                // markup += "<a href=" + Url.Action("postlistsubcategory", new { subcategoryid = num });
            }
            $("#SubCategoryID").html(markup).show();
        },
        error: function (reponse) {
            alert("error : " + reponse);
        }
    });
    $.ajax({
        url: "/Posts/PostListCategory",
        data: { categoryid: _categoryId },
        cache: false,
        type: "POST",
        success: function (data) {
            $("#postList").html(data).show();                
        },
        error: function (reponse) {
            alert("error : " + reponse);
        }
    });
}
</script>
@using (Html.BeginForm())
{    
@Html.ListBoxFor(m => m.CategoryModel, new SelectList(Model.CategoryModel,       "CategoryId", "Name"), new { @id = "ddlcategory", @style = "width:200px;", @onchange = "javascript:GetSubCategory(this.value);" })
<br />
<br />
<div id="SubCategoryID" name="SubCategoryID" style="width: 200px"></div>

<br /><br />

}

在控制器中

public PartialViewResult PostListSubCategory(string subcategoryid)
    {
        if (subcategoryid == null)
        {
            return PartialView(db.Posts.ToList());
        }
        return PartialView("PostList", db.Posts.Include(i => i.SubCategory).Where(p => p.SubCategory.Name == subcategoryid));
    }

1 个答案:

答案 0 :(得分:1)

您目前正在动态生成带有href属性的链接,因此点击它们会进行重定向。您需要使用事件委派处理这些链接的单击事件,然后使用ajax更新现有DOM。您的代码中还有一些其他不良做法,我建议您使用以下

@using (Html.BeginForm())
{
    // no need to override the id attribute and use Unobtrusive Javascript (don't pollute markup with behavior)
    @Html.ListBoxFor(m => m.CategoryModel, new SelectList(Model.CategoryModel,"CategoryId", "Name"))
}
<div id="SubCategoryID"></div> // no point adding a name attribute
<div id="postList"></div>

var subcategories = $('#SubCategoryID');
$('#CategoryModel').change(function() {
    var url = '@Url.Action("GetSubCategoryById", "Posts")'; // don't hard code url's
    var category = $(this).val();
    subcategories.empty(); // clear any existing links
    $.post(url, { categoryid: category }, function(data) { // this could be a GET?
        $.each(data, function(index, item) {
            subcategories.append($('<a></a>').text(item).attr('href','#').addClass('subcategory')); // see note below
        });
    });
});

注意:由于您的ajax只需要一个属性来生成链接(要在链接中显示的值),那么您的GetSubCategoryById()应该返回IEnumerable<string>而不是复杂对象的集合(您当前代码建议您返回其他从未使用的数据)。如果确实需要返回一组对象,请将上面的内容更改为使用.text(item.Text)。上面的代码将生成

<a href="#" class="subcategory">.....</a>

您返回的每件商品。然后添加一个额外的脚本来处理链接的.click()事件(因为链接是动态添加的,您需要使用.on()方法进行事件委派)

var posts = $('#postList');
$('#SubCategoryID').on('click', '.subcategory', function() {
    var url = '@Url.Action("postlistsubcategory", "posts")';
    var subcategory = $(this).text();
    posts.load(url, { subcategoryid: subcategory });
});