c# - .NET MVC 4 - 保持选定对象列表状态的最佳实践

标签 c# .net asp.net-mvc

这应该很简单,但是没有 ViewState,我在这里一无所知(我知道 WebForms 太久了,我知道!)。

我的场景:

查看

 @foreach (var product in Model.Products)
{
    <tr>
       <td>@Html.ActionLink("Compare", "Compare", new { id = product.ProductId })</td>
    </tr>
}

Controller

public ActionResult Compare(int id = 0)
{
        var product = SelectProduct(id); // selects the product from a list of cached products.

        if (product != null)
        {
           // _productDetails is a Model specifically for my View.
            _productDetails.ComparedProducts.Add(product);
        }

        return View("Index", _productDetails);
}

显然,当您为每个项目单击“比较”时,它会添加到 ComparedProducts 列表中。但是,由于没有 ViewState,这将在每次页面刷新时被清除并丢失最后一个产品。我希望产品保留在此 ComparedProducts 列表中,但是如何?

我猜他们需要附加到查询字符串,所以/Carousel/Compare/?id=2122,1221,1331,1333 等。如果是这样,这怎么可能?

提前致谢。

已更新

如果我确实想要使用查询字符串路由,我该怎么做?

我试过:

<td>@Html.ActionLink("Compare", "Compare", new { id = product.ProductId, compared = Model.ComparedProducts.Select(a => a.ProductId) })</td>

但这带来了:

compared=System.Linq.Enumerable%2BWhereSelectListIterator`2[Product%2CSystem.Int32]

我真的很期待。我想我会创建一个进一步的 ViewModel 属性并简单地将比较 ID 存储在那里,以便在我的 View 中没有太多业务逻辑?

最佳答案

+1 表示您与网络表单的关系 :) 我认为从现在开始,您可以开始使用您已经从网络表单了解的其他方式来保持状态,例如 Session State: http://msdn.microsoft.com/en-us/library/ms178581(v=vs.100).aspx

你在querystring上也是对的,毕竟,如果你想保持简单,最好使用最简单的方法,例如:

<url>?reference=123&compare=456

例子

您需要第一个操作作为 HttpGet,现在这个操作作为 httpPOST

[HttpPost]
public ActionResult Compare(myModel model)
{

    var product = SelectProduct(model.reference); // selects the product from a list of cached products.

    if (product != null)
    {
       // _productDetails is a Model specifically for my View.
       // you can always update the model you got in the first place and send it back
        model.ComparedProducts.Add(product); //
    }
return View("Index", model);

你的 View 应该根据要显示的空属性使用react

关于c# - .NET MVC 4 - 保持选定对象列表状态的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13528075/

相关文章:

C# - 进行更快的 MySql 查询?

c# - 绑定(bind) EasingColorKeyframe 值

c# - 使用 Windows 窗体进度条时为 "memory leak"

c# - C# 中的局部静态变量?

asp.net-mvc - ASP MVC 与 Ruby on Rails

C#:是否可以在匿名方法中声明局部变量?

c# - MVVM 将如何用于游戏?

c# - Azure DocumentClient 线程安全

asp.net-mvc - 使用 jQuery getJson 发送列表/数组作为参数

asp.net-mvc - 如何在 asp.net mvc 3 中呈现部分 View ?