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

时间:2019-01-07 08:30:07

标签: c# asp.net-mvc

此代码用于通过List<String>方法传递RedirectToAction

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'

2 个答案:

答案 0 :(得分:0)

您在操作方法上使用了错误的返回类型,因为RedirectToAction要求返回类型为ActionResult而不是List<string>,因为RedirectToRouteResult继承自ActionResult

更新

您需要将列表序列化为JSON字符串以顺利传递(使用Newtonsoft.Json库),因此目标操作方法必须使用string参数。这是将品牌列表发送到其他操作方法的正确设置:

public ActionResult 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();
    return RedirectToAction("BrandsOfACategory", new { brands = JsonConvert.SerializeObject(ListOfBrands) });
}

目标控制器的操作应如下所示:

[HttpGet]
public ActionResult BrandsOfACategory(string brands)
{
    var listOfBrands = JsonConvert.DeserializeObject<List<Brand>>(brands);

    List<string> BrandNames = listOfBrands.Select(f => f.Name.ToString()).ToList();

    // do something and return view
}

参考:

How to pass List in Redirecttoaction

答案 1 :(得分:0)

尝试以下代码,

  string stItems = JsonConvert.SerializeObject(result, Formatting.Indented,
        new JsonSerializerSettings
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
        });
        return ok(stItems);

然后,您可以使用“ BrandsOfACategory”方法从TempData中获取数据到字符串列表。