日期:2014-05-18  浏览次数:20459 次

求Action一问
ASP.netMVC3+EF4,以下代码可以运行,但有些奇怪
有一Action如下:
public ActionResult Edit(int? id)
  {

  List<ClassCategory> categories = context.ClassCategories.ToList();
  for (int i = 0; i < categories.Count; i++)
  {
  categories[i].CategoryName = categories[i].CategoryName.PadLeft(categories[i].CategoryName.Length + (int)categories[i].NodeLevel, ' ');
  }

  ViewBag.ClassCategories = categories;


  if (id.HasValue)
  {
  Regex rgx = new Regex(@"\d+/$");


  ClassCategory cat = context.ClassCategories.SingleOrDefault(c => c.CategoryID == id);
  string parent = rgx.Replace(cat.NodePath, "");

  cat.ParentID = context.ClassCategories.FirstOrDefault(c => c.NodePath == parent).CategoryID;

  return View(cat);
  }
   
  return View(new ClassCategory());
  }

奇怪的地方:
List<ClassCategory> categories = context.ClassCategories.ToList();
  for (int i = 0; i < categories.Count; i++)
  {
  categories[i].CategoryName = categories[i].CategoryName.PadLeft(categories[i].CategoryName.Length + (int)categories[i].NodeLevel, ' ');
  }

  ViewBag.ClassCategories = categories;
这几行代码将得到数据项某字段前加上空格;


下面代码里的ClassCategory实例是从Context上下文得到的,并非前面的List,奇怪的地方在于cat实例的CategoryName前面也有加上的空格:
if (id.HasValue)
  {
  Regex rgx = new Regex(@"\d+/$");


  ClassCategory cat = context.ClassCategories.SingleOrDefault(c => c.CategoryID == id);
  string parent = rgx.Replace(cat.NodePath, "");

  cat.ParentID = context.ClassCategories.FirstOrDefault(c => c.NodePath == parent).CategoryID;

  return View(cat);
  }


------解决方案--------------------
ViewBag是引用类