0

Here's the functionality I'd like to exploit: I've a class myClass and would like to iterate over a collection that contains all the properties of that class. I'd like to send the index of that collection along with the other data so that I can control the each sequence of the iteration.

Here's simplified versions of a Action method and View (I'll use the same action-view for that functionality).

1) Action

public ActionResult CreateHierarchy(int? index)
{

  if(index < PropertiesOfMyClass.Lenght)
  {
    //Other code omitted 

    ViewData["index"] = ((index == null) ? 1 : index++);

    Return View();  
  }
}

2)View

<% Using(Html.BeginForm()){%>      
   //Other Code omitted

   <% = Html.Hidden("Index", ViewData["index"])%>
   <input type = "submit" value = "Do someting"/>
 <%}%>

I've also placed this at the bottom of the page so that I can check the value of the index,

<% = ViewData["index"]%>

Unfortunately, its not working. I'm getting only the number 1. I'm missing something? such as a cast for the Viewdata? Should I write something like this:

<% = Html.Hidden("index", (int)ViewData["index"])%>

It's not working either

=======EDIT April 6th/08h37AM

myClass's real name is Hierarchy, which contains several levels like this

public class Hierarchy
{
public int HierarchyID { get; set;}
public string Level1 { get; set; }
public string Level2 { get; set; }
        ----
public string Level7 { get; set; }
}

Once I've the above properties in a collection, I can iterate that collection from Level1 to Level7 by turn (as value for each Level can have numerous sources). The index is important for me as rely on it to move forward or backward.

Also I provided both the logic (1) in the action and in the View(2), so that one can follow how the index is passed back and forth between the action and the View.

Thanks for helping

4

2 回答 2

1

您最初传递给此 Action 方法的值是 1 吗?如果是这样,当您使用 ++ 操作作为后缀操作时,您将始终返回 1。也就是说,在分配给 ViewData 后,该值将增加。如果您执行前缀操作,您的问题应该得到解决,当然前提是我的上述前提是正确的。

有关前缀与后缀操作的详细信息,请参阅MSDN 上的 ++ 运算符文章

我还应该指出,您的布尔表达式将始终评估为 false,因为 Nullable<T> == null 始终为 false。相反,您应该考虑将该表达式修改为(或类似的):

ViewData["index"] = ((index.HasValue) ? index.Value + 1 : 1);
于 2010-04-06T12:50:15.777 回答
0

在查看其他论坛后,我被提醒 ViewData 具有价值,以便在出现问题时可以将其显示回来。为了获得我想要的功能,我需要先清除 ViewData,使用以下语句:

ViewData.ModelState.Clear();
ViewData["index"] = index + 1; 

或者

ModelState.Remove("index")
ViewData["index"] = index + 1;

第二个语句更好,因为它只处理一个条目(而不是清除整个 ViewData 字典)。之后,我可以重新分配一个新值 = index + 1(如果我使用 Clear())或重新创建一个名为ViewData["index"]的新条目并将值index + 1分配给它。

感谢您的所有回答。

于 2010-04-07T13:48:54.063 回答