2012-09-18 103 views
0

我将List<Listing>对象传递给另一个操作方法,并使该方法使用该参数调用View。ASP.NET MVC null参数

出于某种原因,我传递的参数为null。

下正常工作:

 public ActionResult SortListing(string categoryGuid) 
    { 
     var listingCategory = new ListingCategory(); 
     listingCategory = _tourismAdminService.GetByGuid<ListingCategory>(Guid.Parse(categoryGuid)); 
     var listings = new List<Listing>(); 

     foreach (var listing in _tourismAdminService.ListAllEntities<Listing>()) 
     { 
      if (listing.CategoryId == listingCategory.Id) 
      { 
       listings.Add(listing); 
      } 
     } 

     return RedirectToAction("Index", "Listing", listings); 
    } 

下面显示了就要到了为空的参数。

 public ActionResult Index(List<Listing> listing) 
    { 
     var model = new ListListingsViewModel(); 
     IEnumerable<ListingCategory> categories = _service.ListAllEntities<ListingCategory>(); 

     if (categories != null) 
     { 
      model.Categories = 
       categories.Select(
        cat => 
        new SelectListItem 
         { 
          Text = 
           cat.GetTranslation(stringA, 
                stringB).Name, 
          Value = cat.Guid.ToString() 
         }).ToList(); 
     } 
     model.Listings = listing ?? _service.ListAllEntities<Listing>(); 

     return View(model); 
    } 

EDIT

错误消息:

具有密钥的ViewData项 'SelectedCategoryGuid' 的类型为 '的System.Guid',但必须是类型为 'IEnumerable的'。

开:

@Html.DropDownListFor(
m => m.SelectedCategoryGuid, 
Model.Categories, 
"Select a Category", 
new { 
    id = "hhh", 
    data_url = Url.Action("SortListing", "Listing") 
} 
) 

回答

2

RedirectToAction方法返回一个HTTP 302响应于所述浏览器,这会导致浏览器进行GET请求来指定的操作。

请记住HTTP是无状态的。你不能像这样传递这样复杂的对象。

您应该传递查询字符串(Id)并再次获取第二个操作中的值或将数据保存在调用之间的persitant媒体中。您可以考虑使用会话或TempData(会话是备份的存储)。

http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications

编辑:按注释。是的,您可以从第一种方法本身调用视图。下面的代码将传递字符串集合Index视图(index.cshtml)。

public ActionResult SortedList(string categoryGuid) 
{ 
    var listings = new List<Listing>(); 
    //fill the collection from the data from your db 
    return View("Index",listings) 
} 

如果你想将数据传递给视图在不同的控制器,可以调用浏览方法时指定的完整路径。

return View("~/Views/User/Details.cshtml",listings) 

假设你的看法是强类型到strings列表这样

@model List<string> 
foreach(var item in Model) 
{ 
<p>@item</p> 
} 
+0

您好。我喜欢你的查询字符串的第一个例子。你能否通知我如何做到这一点?你能否告诉我是否可以从第一种方法调用View,因为我不需要第二种方法叫 – Subby

+0

@Subby:是的。看到我更新的答案。 – Shyju

+0

嘿Shyju。请检查我的更新是否有新错误 – Subby