使用按钮加载视图单击新页面MVC

时间:2017-07-27 19:21:12

标签: javascript c# asp.net-mvc entity-framework

在点击包含帖子的主页时,最好的方法或可能的java脚本可以加载视图(文章)。

我发现大多数文档都在同一视图中的div上加载视图。

帖子查看:

<div class="row small-up-2 medium-up-3">
    @foreach (var post in Model.Posts)
    {
            <div class="column column-block">
                <div class="blog-post">
                    <img src="https://placeimg.com/400/400/cba" alt="">
                    <h3>@post.Title</h3>
                    <img src=@post.Image alt="">

                    <button data-url='@Url.Action("SearchPartial","Blog", @post.Title )'
                            class="button js-reload-details">
                        Reload
                    </button>
                </div>
        </div>
    }

加载文章视图的控制器:

public ActionResult SearchPartial(String title)
        {
            var model = db.Posts.Where(x => x.Title == title).FirstOrDefault();


            return View("SearchPartial", model);
        }

1 个答案:

答案 0 :(得分:1)

不使用按钮,而是使用HTML元素的本机行为,并使用锚标记。它们旨在将您发送到新位置,并且可以轻松点击您的Controller并将浏览器移动到其他位置。

使用CSS,您可以轻松地使它们看起来像其他按钮。我将添加属于Bootstrap的类。

此外,您应该发送帖子的ID而不是标题。这是一个唯一值,很可能,您对Title属性没有相同的约束。标题可以搜索,但是你不应指望那些指向一个且只有一个帖子。

<div class="row small-up-2 medium-up-3">
    @foreach (var post in Model.Posts)
    {
        <div class="column column-block">
            <div class="blog-post">
                <img src="https://placeimg.com/400/400/cba" alt="">
                <h3>@post.Title</h3>
                <img src=@post.Image alt="">

                // Send the post.Id instead of post.Title
                <a href='@Url.Action("SearchPartial","Blog", new { id = @post.Id } )' class="btn btn-primary">
                    Reload
                </a>
            </div>
    </div>
}

通过更改链接的参数,您还需要更改操作方法。

public ActionResult SearchPartial(int postId)
{
    var model = db.Posts.Find(postId);

    return View("SearchPartial", model);
}
相关问题