在 ASP.Net MVC 中的操作后替换部分视图

发布于 2024-12-04 06:26:52 字数 470 浏览 3 评论 0原文

我对 ASP.NET MVC 还很陌生,想知道如何实现以下目标: 在作为母版页一部分的普通视图上,我使用循环创建了不同数量的部分视图,每个视图代表用户应该能够投票的项目。单击投票按钮后,评级将提交到数据库,然后用户单击的特定部分视图将被相同的视图替换,并更改一些视觉属性。实现这一目标的最佳实践是什么?

我是这样开始的: 1. 我使用 if 语句定义了部分视图,根据特定视图模型中的标志区分视觉外观。因此,如果标志为正,则显示投票控件,如果为负,则不显示。

  1. 我将 Url.Action(..) 分配给触发控制器方法的投票按钮。在此方法中,新的评级将添加到数据库中。

  2. 在控制器方法中,我返回带有更新的 ViewModel 的 PartialView。不幸的是,整个视图都被替换,而不仅仅是部分视图。

任何关于如何解决这个特定问题或如何实现整个事情的建议将受到高度赞赏。

非常感谢, 克里斯

I'm still quite new to ASP.NET MVC and wonder how-to achieve the following:
On a normal view as part of my master page, I create a varying number of partial views with a loop, each representing an item the user should be able to vote for. After clicking the vote-button, the rating shall be submitted to the database and afterwards, the particular partial view which the user clicked shall be replaced by the same view, with some visual properties changed. What is the best practice to achieve this?

Here's how I started:
1. I defined the partial view with an if-sentence, distinguishing between the visual appearance, depending on a flag in the particular viewmodel. Hence, if the flag is positive, voting controls are displayed, if it's negative, they're not.

  1. I assigned a Url.Action(..) to the voting buttons which trigger a controller method. In this method, the new rating is added to the database.

  2. In the controller method, I return the PartialView with the updated ViewModel. UNFORTUNATELY, the whole view get's replaced, not only the partial view.

Any suggestions how-to solve this particular problem or how-to achieve the whole thing would be highly appreciated.

Thanks very much,
Chris

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

懒猫 2024-12-11 06:26:52

解决您的问题的简单(但无论如何都是正确且可用的)解决方案是 Ajax.BeginForm() 投票助手。通过这种方式,您可以将投票更改为 ajax 调用,并且可以轻松指定此调用返回的结果(来自您的投票操作,将返回仅包含 1 个更改项目的部分视图)将用于替换旧内容(例如投票前包含旧项目的特定 div)。

更新 - 2016 年 11 月 30 日

例如:

@using (Ajax.BeginForm("SomeAction", "SomeController", new { someRouteParam = Model.Foo }, new AjaxOptions { UpdateTargetId = "SomeHtmlElementId", HttpMethod = "Post" }))

Trivial (but by all means correct and usable) solution to your problem is Ajax.BeginForm() helper for voting. This way you change your voting to ajax calls, and you can easily specify, that the result returned by this call (from your voting action, which will return partial view with only 1 changed item) will be used to replace old content (for example one particular div containing old item before voting).

Update - 11/30/2016

For example:

@using (Ajax.BeginForm("SomeAction", "SomeController", new { someRouteParam = Model.Foo }, new AjaxOptions { UpdateTargetId = "SomeHtmlElementId", HttpMethod = "Post" }))
绳情 2024-12-11 06:26:52

ASP.NET MVC 是满足这种需求的完美框架。如果我处于您的位置,我会做的就是使用 JQuery Ajax API。

以下博客文章应该会提示您如何使用 PartialViews、JQuery 和 Ajax 调用服务器:

http://www.tugberkugurlu.com/archive/working-with-jquery-ajax-api-on-asp-net-mvc-3-0-power-of-json-jquery-and- asp-net-mvc-partial-views

更新

有人要求做一个简短的介绍,所以就在这里。

以下代码是您的操作方法:

    [HttpPost]
    public ActionResult toogleIsDone(int itemId) {

        //Getting the item according to itemId param
        var model = _entities.ToDoTBs.FirstOrDefault(x => x.ToDoItemID == itemId);
        //toggling the IsDone property
        model.IsDone = !model.IsDone;

        //Making the change on the db and saving
        ObjectStateEntry osmEntry = _entities.ObjectStateManager.GetObjectStateEntry(model);
        osmEntry.ChangeState(EntityState.Modified);
        _entities.SaveChanges();

        var updatedModel = _entities.ToDoTBs;

        //returning the new template as json result
        return Json(new { data = this.RenderPartialViewToString("_ToDoDBListPartial", updatedModel) });
    } 

RenderPartialViewToString是控制器的扩展方法。你
这里需要使用 Nuget 来下载一个非常小的包,名为
TugberkUg.MVC 它将有一个控制器扩展供我们转换
控制器内部字符串的部分视图。

然后,这里是有关如何使用 JQuery 调用它的简要信息:

var itemId = element.attr("data-tododb-itemid");
var d = "itemId=" + itemId;
var actionURL = '@Url.Action("toogleIsDone", "ToDo")';

$("#ajax-progress-dialog").dialog("open");

$.ajax({
    type: "POST",
    url: actionURL,
    data: d,
    success: function (r) {
        $("#to-do-db-list-container").html(r.data);
    },
    complete: function () {
        $("#ajax-progress-dialog").dialog("close");
        $(".isDone").bind("click", function (event) {
            toggleIsDone(event, $(this));
        });
    },
    error: function (req, status, error) {
        //do what you need to do here if an error occurs
        $("#ajax-progress-dialog").dialog("close");
    }
});

需要采取一些额外的步骤。因此,请查看包含完整演练的博客文章。

ASP.NET MVC is a perfect framework for this kind of needs. What I would do if I were in your possition is to work with JQuery Ajax API.

Following blog post should give you a hint on what you can do with PartialViews, JQuery and Ajax calls to the server :

http://www.tugberkugurlu.com/archive/working-with-jquery-ajax-api-on-asp-net-mvc-3-0-power-of-json-jquery-and-asp-net-mvc-partial-views

UPDATE

It has been asked to put a brief intro so here it is.

The following code is your action method :

    [HttpPost]
    public ActionResult toogleIsDone(int itemId) {

        //Getting the item according to itemId param
        var model = _entities.ToDoTBs.FirstOrDefault(x => x.ToDoItemID == itemId);
        //toggling the IsDone property
        model.IsDone = !model.IsDone;

        //Making the change on the db and saving
        ObjectStateEntry osmEntry = _entities.ObjectStateManager.GetObjectStateEntry(model);
        osmEntry.ChangeState(EntityState.Modified);
        _entities.SaveChanges();

        var updatedModel = _entities.ToDoTBs;

        //returning the new template as json result
        return Json(new { data = this.RenderPartialViewToString("_ToDoDBListPartial", updatedModel) });
    } 

RenderPartialViewToString is an extension method for controller. You
need to use Nuget here to bring down a very small package called
TugberkUg.MVC which will have a Controller extension for us to convert
partial views to string inside the controller.

Then here is a brief info on how you can call it with JQuery :

var itemId = element.attr("data-tododb-itemid");
var d = "itemId=" + itemId;
var actionURL = '@Url.Action("toogleIsDone", "ToDo")';

$("#ajax-progress-dialog").dialog("open");

$.ajax({
    type: "POST",
    url: actionURL,
    data: d,
    success: function (r) {
        $("#to-do-db-list-container").html(r.data);
    },
    complete: function () {
        $("#ajax-progress-dialog").dialog("close");
        $(".isDone").bind("click", function (event) {
            toggleIsDone(event, $(this));
        });
    },
    error: function (req, status, error) {
        //do what you need to do here if an error occurs
        $("#ajax-progress-dialog").dialog("close");
    }
});

There needs to be some extra steps to be taken. So look at the blog post which has the complete walkthrough.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文