在 ASP.NET-MVC 中使用 RedirectToAction 传递字符串类型列表

此代码用于传递List<String>withRedirectToAction方法:


public List<String> ListOfBrandNames(string id)

    {

        var result = db.Items.Where(x => x.Category.Name.Equals(id)).Select(x => x.BrandID).ToList();

        var ListOfBrands = db.Brands.Where(t => result.Contains(t.BrandID)).ToList();

        List<String> BrandNames = ListOfBrands.Select(f => f.Name.ToString()).ToList();

        return RedirectToAction("BrandsOfACategory", new { brands = BrandNames });

    }

RedirectToAction方法抛出此错误:


无法将类型“System.Web.Mvc.RedirectToRootResult”隐式转换为“System.Collection.Generic.List”


吃鸡游戏
浏览 95回答 2
2回答

ITMISS

您在操作方法上使用了错误的返回类型,因为RedirectToAction需要返回类型ActionResult而不是List<string>因为RedirectToRouteResult继承自ActionResult.更新:您需要将列表序列化为 JSON 字符串才能顺利传递(带Newtonsoft.Json库),因此目标操作方法必须使用string参数。这是将品牌列表发送到另一个操作方法的正确设置:public ActionResult ListOfBrandNames(string id){&nbsp; &nbsp; var result = db.Items.Where(x => x.Category.Name.Equals(id)).Select(x => x.BrandID).ToList();&nbsp; &nbsp; var ListOfBrands = db.Brands.Where(t => result.Contains(t.BrandID)).ToList();&nbsp; &nbsp; return RedirectToAction("BrandsOfACategory", new { brands = JsonConvert.SerializeObject(ListOfBrands) });}目标控制器动作应该是这样的:[HttpGet]public ActionResult BrandsOfACategory(string brands){&nbsp; &nbsp; var listOfBrands = JsonConvert.DeserializeObject<List<Brand>>(brands);&nbsp; &nbsp; List<string> BrandNames = listOfBrands.Select(f => f.Name.ToString()).ToList();&nbsp; &nbsp; // do something and return view}

天涯尽头无女友

试试下面的代码,public List<String> ListOfBrandNames(string id){&nbsp; &nbsp; var result = db.Items.Where(x => x.Category.Name.Equals(id)).Select(x => x.BrandID).ToList();&nbsp; &nbsp; var ListOfBrands = db.Brands.Where(t => result.Contains(t.BrandID)).ToList();&nbsp; &nbsp; List<String> BrandNames = ListOfBrands.Select(f => f.Name.ToString()).ToList();&nbsp; &nbsp; TempData["Brands"]=BrandNames;&nbsp; &nbsp; return RedirectToAction("BrandsOfACategory");}之后,您可以从 TempData 获取数据到“BrandsOfACategory”方法中的字符串列表。
打开App,查看更多内容
随时随地看视频慕课网APP